c - Returning an address of a local pointer variable to main() function -
in following example, function func() returning address of local pointer variable main() function. it's working fine in gcc.
so, is well-defined behaviour?
#include <stdio.h> #include <stdlib.h> int *func(void); int *func(void) { int *p; p = malloc(sizeof *p); *p = 10; return p; } int main() { int *ptr = func(); printf("%d\n",*ptr); return 0; }
inside func(), p pointer memory allocated malloc() (or potentially allocated memory, since malloc() can fail, returning null pointer; should checked for). if successful, memory allocation persist until explicitly freed.
the value of p returned calling function, main() in case. p either pointer successful allocation, or null pointer, , returned value (which temporary, , not lvalue) assigned ptr. so, allocated storage can accessed through ptr, copy of value held p before func() returned, though lifetime of p has ended func() has returned.
of course ptr should freed when no longer needed avoid memory leaks. and, there potential undefined behavior here if malloc() fails, since ptr null pointer.
Comments
Post a Comment