c - Simple test of malloc and free with int pointer causes double free or corruption error -


to learn more pointers wrote simple test function creates pointer, allocates space ande after output on shell space shall freed.

void main() {   int *p = (int*) malloc(sizeof(int));   int = 42;   printf("p: %x\n", p);   printf("*p: %d\n", *p);   printf("a: %s\n", a);   printf("&a: %x\n", &a);   p = &a;   printf("p: %x\n", p);   printf("*p: %x\n", *p);    //until works expected   free(p); //error   // printf("p: %x\n", p); // shall cause error, because space freed   // printf("*p: %x\n", *p); // shall cause error, because space freed } 

at first runs ok. free(p) caused no error. tried same test struct , got double free error. "ok, maybe wrong, lets go start", thought , ctrl+z 1 above, before. still error. why? thats newbie question, know. code above can find everywhere in web simple demonstration of malloc , free. here: http://www.cplusplus.com/reference/cstdlib/free/ hope, can tell me wrong.

the pointer passed free() must returned previous call malloc() (or calloc() or realloc()). not case p has address of a after:

p = &a; 

and p passed free() causing undefined behaviour.

note in example on page linked in question pointer being reassigned after call of dynamic allocation functions.


the comment "shall cause error, because space freed" in following code snippet incorrect:

free(p); //error // printf("p: %x\n", p); // shall cause error, because space freed 

as safe print address of pointer, regardless of whether memory has been associated has been free() or not. is error if attempt access memory has been free()d, comment correct:

// printf("*p: %x\n", *p); // shall cause error, because space freed 

because p being deferenced , attempt read free()d memory occurring.


this error:

printf("a: %s\n", a); /* must '%d' 'a' 'int'. */ 

note that:

printf("p: %x\n", p); 

is undefined behaviour: use %p format specifier pointers. see correct format specifier print pointer (address)?


do cast result of malloc?


Comments

Popular posts from this blog

Perl - how to grep a block of text from a file -

delphi - How to remove all the grips on a coolbar if I have several coolbands? -

javascript - Animating array of divs; only the final element is modified -