free() not freeing up memory properly?

2019-02-24 06:15发布

问题:

I'm trying to free up the memory I've allocated with malloc, but the free command doesn't seem to do its job properly according to Eclipse's debugger. How's this possible?

Below is a screenshot of my debugger after it supposedly freed up seCurrent->student->year, which is clearly not the case. year was allocated using malloc.

alt text http://img693.imageshack.us/img693/7840/codeo.png

回答1:

free() does not normally change any values in your program - it just makes adjustments to the C runtime heap. This means that the values in the memory that was just freed are retained. However, attempts to access them from your code lead to undefined behaviour.



回答2:

What makes you think it hasn't freed it? Freeing memory means that accessing it from the program thereafter is undefined behavior, and the memory is available for re-use next time you call malloc. It does not promise to overwrite the data that was stored in the memory you freed, or to prevent the debugger from reading the unallocated memory.



回答3:

Free will return the allocated space to the heap to be reused by subsequent mallocs but it does not change the values of any pointers that previously referenced that memory. In your case, no other mallocs have yet been performed so the memory just freed is still the same as it was just prior to the call to free. In order for your code to know that there is no longer any data associated with the pointer, you may want to set it to null after freeing the memory associated with it.



回答4:

when you malloc() some memory, all it does is searching for some free space in memory, and keeping track it is now used. It doesn't initialize it or whatever.

when you call free(), all it does is clearing this memory block out of the list of used memory blocks. Again it doesn't modify the contents.