c - Free memory before returning -
this question has answer here:
- using pointer after free() 5 answers
suppose have following program
#include <stdlib.h> #include <stdio.h> #include <string.h> char *returnsomething() { char *mystring; mystring = malloc(sizeof(char) * 50); strcpy(mystring,"hello"); free(mystring); return mystring; } int main(int argc, char const *argv[]) { char *mystring = returnsomething(); printf("%s",mystring); return 0; }
why print "hello" when free'd before returning? thought woudn't print since free'd memory returned string afterwards. assumed had free in main after printing it.
is mac compiler being nice?
when call free(mystring), memory mystring points being freed, value of mystring stays untouched, making mystring dangling pointer. accessing memory has been freed can produces undefined behavior.
Comments
Post a Comment