0

Consider the following code:

#include <stdlib.h>

int main() {
    int* p = (int*)malloc(10 * sizeof(int));
    printf("P = 0x%p\n", p); // prints some address
    p[0] = 0;
    printf("P[0] = %d\n", *p); // prints 0
    free(p);
    printf("P = 0x%p\n", p); // prints same address
    printf("P[0] = %d", *p); // prints -572662307 always
}

Why does the value of *p change so quickly after freeing up the memory?

I know it's undefined behavior to access and change freed memory. I'm just asking how come that cell always gets garbage written into it every time?

hadizadeh.ali
  • 63
  • 1
  • 8
  • 4
    Reading of freed memory results in _undefined behaviour_ which includes "the freed memory is overwritten by some data". – Jabberwocky Apr 23 '20 at 11:43
  • 1
    "_prints same address_" Why wouldn't it? You didn't change `p`. – Algirdas Preidžius Apr 23 '20 at 11:45
  • 3
    -572662307 is 0xDDDDDDDD. See this answer for other magic values: [In Visual Studio C++, what are the memory allocation representations?](https://stackoverflow.com/questions/127386/in-visual-studio-c-what-are-the-memory-allocation-representations) – Botje Apr 23 '20 at 11:47
  • But what probably happens here is that the freed memory is overwritten by the special pattern `0xdddddddd` which is facilitates debugging in the case that the freed memory is continued to be used. – Jabberwocky Apr 23 '20 at 11:47
  • I suspect those magic numbers in memory are a result of a DEBUG build and the debug runtime library. They're probably different in a RELEASE build. – Blastfurnace Apr 23 '20 at 11:53
  • @Lundin "someone" being `free`, to *very helpfully* show you that dereferencing an invalid pointer has undefined behaviour – Caleth Apr 23 '20 at 12:08

0 Answers0