free() not freeing up memory properly?

2019-02-24 06:35发布

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

4条回答
Bombasti
2楼-- · 2019-02-24 06:49

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.

查看更多
Fickle 薄情
3楼-- · 2019-02-24 06:56

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.

查看更多
不美不萌又怎样
4楼-- · 2019-02-24 07:00

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.

查看更多
女痞
5楼-- · 2019-02-24 07:09

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.

查看更多
登录 后发表回答