Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy do I get different results when I dereference a pointer after freeing it?
    primarykey
    data
    text
    <p>I've a question about the memory management in C (and GCC 4.3.3 under Debian GNU/Linux). </p> <p>According to the C Programming Language Book by K&amp;R, (chap. 7.8.5), when I free a pointer and then dereference it, is an error. But I've some doubts since I've noted that sometimes, as in the source I've pasted below, the compiler (?) seems to work according a well-defined principle. </p> <p>I've a trivial program like this, that shows how to return an array dynamically allocated:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; int * ret_array(int n) { int * arr = (int *) malloc(10 * sizeof(int)); int i; for (i = 0; i &lt; n; i++) { arr[i] = i*2; } printf("Address pointer in ret_array: %p\n", (void *) arr); return arr; } int * ret_oth_array(int n) { int * arr = (int *) malloc(10 * sizeof(int)); int i; for (i = 0; i &lt; n; i++) { arr[i] = i+n; } printf("Address pointer in ret_oth_array: %p\n", (void *) arr); return arr; } int main(void) { int *p = NULL; int *x = NULL; p = ret_array(5); x = ret_oth_array(6); printf("Address contained in p: %p\nValue of *p: %d\n", (void *) p, *p); free(x); free(p); printf("Memory freed.\n"); printf("*(p+4) = %d\n", *(p+4)); printf("*x = %d\n", *x); return 0; } </code></pre> <p>If I try to compile it with some arguments: <code>-ansi -Wall -pedantic-errors</code>, it doesn't raises errors or warning. Not only; it also runs fine.</p> <pre><code>Address pointer in ret_array: 0x8269008 Address pointer in ret_oth_array: 0x8269038 Address contained in p: 0x8269008 Value of *p: 0 Memory freed. *p+4 = 8 *x = 0 </code></pre> <p>*(p+4) is 8 and *x is 0. Why does this happen? If *(p+4) is 8, shouldn't *x be 6, since the first element of the x-array is 6?</p> <p>Another strange thing happens if I try to change the order of the calls to free. E.g.:</p> <pre><code>int main(int argc, char * argv[]) { /* ... code ... */ free(p); free(x); printf("Memory freed.\n"); printf("*(p+4) = %d\n", *(p+4)); printf("*x = %d\n", *x); return 0; } </code></pre> <p>In fact in this case the output (on my machine) will be:</p> <pre><code>*p+4 = 8 *x = 142106624 </code></pre> <p>Why does the <em>x</em> pointer is really "freed", while the p pointer is freed (I hope) "differently"? Ok, I know that after freeing memory I should make the pointers to point to NULL, but I was just curious :P</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload