Re: writing to freed memory--issues



bill pursell wrote:
I was playing around with a toy program, which led to some confusion.
I had expected that doing the following would lead to an immediate
segfault:
free(a);
*a=0;
In C jargon, you're invoking undefined behavior. Anything could happen.
This means it could work as expected. Blow up. Blow up later. Cause
unpredictable behavior on further operations. etc.
The other day I was debugging a program that ran as normal,
except it outputted dynamic linker statistics at the end.
Turned out a wild pointer overwrote some data ld.so should be using.

However, it did not. Further investigation showed that I could free a
and then write to a[0] through a[1022] without difficulty, but writing
to a[1023] caused a segfault. I concluded that when I had allocated
Lucky you.

enough space that the process required an extra page, the page was
given, and then taken back on the free, so that writes to the freed
page caused the error. Since a[0] through a[1022] were on the page
still allocated to the process, there was no error writing to them.

However, I then wrote the same toy on a different box (Fedora, whereas
the first toy was done on a debian), and got wildly different results.
I cannot explain the behavior, and am hoping someone might have some
insight.
That's undefined behavior for you. Who knows what will happen - better
code things right.
.