If your program tries to read from or write to memory that was previously freed, the program will generate a memory error.
For example, if it calls the free function for a particular block and then continues to use that block,
the program will create a memory reuse problem when a malloc call is next made.
Consequences
Using freed memory generates the following runtime errors:
- memory corruption (may cause an unpredictable failure in the future)
- random data read (when a heap block is re-used, other data can be in that location)
Detecting the error
Depending on which error checks are enabled under
Memory Errors in the configuration,
the Memory Analysis tool can detect when free memory is read from or written to in the following conditions:
- Verify parameters in string and memory functions—when library functions read memory
referred to by a pointer that's known to be free
- Enabled bounds checking (where possible)—when a newly allocated block contains
altered data, meaning it was modified after it was previously deallocated
For the list of functions that trap these error conditions, see the Trap Function field, below.
Information returned by the Memory Problems view
The notification for this type of memory error includes the following details:
- Severity: ERROR
- Description: data in freed memory block has been modified
- Pointer: address of the freed memory block
- Trap Function: one of:
malloc
calloc
realloc
free
strcat
strdup
strncat
strcmp
strncmp
strcpy
strncpy
strlen
strchr
strrchr
index
rindex
strpbrk
strspn
strcspn
strstr
strtok
memccpy
memchr
memmove
memcpy
memcmp
memset
bcopy
bzero
bcmp
- Alloc Kind: how memory was allocated for this block (malloc, calloc,
or realloc)
- Location: source file and line of code where the error occurred (e.g., main.c:59)
- Count: number of blocks involved
How to address freed memory usage
Set the pointer of the freed memory to NULL immediately after the call to free, unless it's
a local variable that goes out of scope in the next line of the program.
Example
The following code shows an example of using freed memory:
int main(int argc, char ** argv) {
char * ptr = NULL;
ptr = malloc(13);
free(ptr);
strcpy(ptr,"Hello World!");
return 0;
}