Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
728 views
in Technique[技术] by (71.8m points)

c - What happens to the data in memory deallocated by free()?

What happens to the data that is present in a memory location that has just been freed by a free() ? Is that data also deleted and the memory will now have a garbage value ? Or that data still persists there untill a new data is stored in that memory location (in future) ?

I mean, for code below:

int *ptr;
ptr = malloc(sizeof(int));
*ptr = 1;
 // Suppose ptr = 2000
 //Free now
free(ptr);
// My question is what is the value stored in memory address 2000 now ?
// Is it still '1' or some garbage value ?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The result is unpredictable. There are several options that can happen. The point is that you cannot rely on any behavior of the memory released by free()

Some examples:

  • the memory can be untouched (remain the same as it is with the same data).
  • It can be given to another memory allocation, in which case it can be written over at any point.
  • It can be zeroed.
  • The page containing the memory can be returned to the OS, removing it from the memory map of your process, making your program crash if you try to access it.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...