c - Why does a pointer variable when after freeing it stores the new address of its previous address stored? -


i have 2 questions.

  1. how free function in c work?
  2. 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 pointed ptr 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,

  1. to print pointer, should use %p format specifier , cast argument void*.
  2. please see discussion on why not cast return value of malloc() , family in c..

Comments

Popular posts from this blog

javascript - Laravel datatable invalid JSON response -

java - Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; -

sql server 2008 - My Sql Code Get An Error Of Msg 245, Level 16, State 1, Line 1 Conversion failed when converting the varchar value '8:45 AM' to data type int -