Correct use of free() in complex structures
Consider the following program:
Code:
#include <stdlib.h> When I compile this program with the option "-Wall" included I get no error or warning messages and when when run the program runs as expected so all seems OK. However when I run the same program under Valgrind I get warned of a memory leak. This makes sense as the CharString pointer has not been freed up. To handle this leak I added an extra free() command specifically for that pointer so the program now looks like this: Code:
. Code:
*** glibc detected *** free(): invalid pointer: 0x080485b4 *** Code:
. |
The problem is not with free() but because you lose the malloc you originally gave to CharString.
malloc() returns a pointer to the address of the memory reserved. So you set CharString equal to that. That's perfectly legit. Then you do this: Code:
TestStruct->CharString = "Hello World!\n\n\n"); By using the assignment operator, you lose the address of the memory you malloc'ed, and replace it with the address where "Hello World\n\n\n" is stored (which is likely kept inside the executable itself). |
OK, I've changed the program so that it now reads:
Code:
#include <stdlib.h> |
All times are GMT -5. The time now is 12:13 AM. |