c - Free memory before returning -


this question has answer here:

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.

using pointer after free()


Comments

Popular posts from this blog

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -

python - Error while using APScheduler: 'NoneType' object has no attribute 'now' -