If you attempt to read or write to memory that was previously freed, the result will be a conflict and the program will generate a memory error. For example, if a program calls the free() function for a particular block and then continues to use that block, it will create a reuse problem when a malloc() call is made.
Consequences
Using freed memory generates the following runtime errors:
Detecting the error
The Memory Analysis tool can detect only a limited number of situations where free memory is read/written with following conditions:
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()
malloc() calloc() realloc() free()
Enabling error detection
To enable error detection when using freed memory:
Message returned to the IDE
In the IDE, you can expect the message for this type of memory error to include the following types of information and detail:
For a list of error messages returned by the Memory Analysis tool, see Summary of error messages for Memory Analysis.
How to address freed memory usage
Set the pointer of the freed memory to NULL immediately after the call to free(), unless it is a local variable that goes out of the scope in the next line of the program.
Example
The following code shows an example using already freed memory:
int main(int argc, char ** argv){ char * ptr = NULL; ptr = malloc(13); free(ptr); strcpy(ptr,"Hello World!"); return 0; }