cmemory-managementstackautomatic-storage

function returning a pointer to automatic variable


So I am working with a "standard" library with more than a decade of history for brain image I/O. I encountered this function:

   nifti_image* nifti_image_read( const char *hname , int read_data ){

   nifti_image* nim;
...

<<<some IO operations>>>

...

return nim;
}

My question is, how come this function is returning a local pointer to an automatic variable? Isn't this practice prohibited since the nim pointer goes out of scope and is supposed to be deleted after completion of the function?

I have already read this question but couldn't get my answer:


Solution

  • This function is returning the value stored in the pointer and it is ok. The pointer value is the address of an object which is probably a allocated dynamically and is NOT deleted at the end, even if it was C++. The only possible issue is the case where the pointer points to another local variable, not allocated dynamically. So even though the pointer itself goes out of scope, the caller that receives the return value gets a copy of the address of a valid object.