Sourena
Sourena

Reputation: 25

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:

Upvotes: -1

Views: 269

Answers (3)

Elvis Teixeira
Elvis Teixeira

Reputation: 614

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.

Upvotes: 0

dbush
dbush

Reputation: 223699

You're not returning a pointer to a local variable. You're returning the value of a local variable which happens to be a pointer.

Assuming the pointer is not pointing to another local variable itself, this is a safe operation.

Upvotes: 0

cleblanc
cleblanc

Reputation: 3688

It's just returning the value of the nim pointer.
During the << some IO operations >> part I assume nim is set to point at some permanent memory in the heap or global.

Upvotes: 1

Related Questions