c - Why does a pointer variable when after freeing it stores the new address of its previous address stored? -
i have 2 questions.
- how
free
function in c work? - how come pointer variable updates store new address?
this code:
#include <stdio.h> #include <stdlib.h> int main() { int a; int *p; p = (int *)malloc(sizeof(int)); *p = 10; int *q = p; printf("p:%d\n", p); printf("q:%d\n", q); printf("*p:%d\n", *p); printf("*q:%d\n", *q); free(p); printf("memory freed.\n"); p = (int *)malloc(sizeof(int)); *p = 19; printf("p:%d\n", p); printf("q:%d\n", q); printf("*p:%d\n", *p); printf("*q:%d\n", *q); }
how come output this?
p:2067804800 q:2067804800 *p:10 *q:10 memory freed. p:2067804800 q:2067804800 *p:19 *q:19
once call free()
on malloc()
-ed pointer, memory (returned pointer) free re-allocated subsequent call malloc()
family. that's whole point of having free()
.
quoting c11
, chapter §7.22.3.3
the
free
function causes space pointedptr
deallocated, is, made available further allocation. [....]
so, quite possible, after free()
, when malloc()
-ed again same pointer same amount of memory, same pointer returned. there's no surprise.
(and knows, if compiler smart enough, can remove ineffective free(p);
, p = (int*)malloc(sizeof(int));
altogether)
next, in last line of code,
printf("*q:%d\n", *q);
you invoke undefined behavior attempting access (dereference) free-d memory. don't that.
that said,
- to print pointer, should use
%p
format specifier , cast argumentvoid*
. - please see discussion on why not cast return value of
malloc()
, family inc
..
Comments
Post a Comment