-1

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:

Sourena
  • 25
  • 1
  • 5
  • It's returning a a copy of num by value. Presumably, the 'some IO operations' loads num with the address of some data whose lifetime can exceed that of 'nifti_image_read()'. That's just fine, and then, so is returning its address. – ThingyWotsit Apr 05 '17 at 20:10
  • @ThingyWotsit I did some research on returning by value vs. by reference and got the point now. Thanks. – Sourena Apr 05 '17 at 20:27

3 Answers3

1

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.

cleblanc
  • 3,678
  • 1
  • 13
  • 16
0

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.

dbush
  • 205,898
  • 23
  • 218
  • 273
0

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.

Elvis Teixeira
  • 604
  • 4
  • 13
  • So I guess the same function but which returns by reference like: nifti_image*& nifti_image_read() would be wrong? – Sourena Apr 05 '17 at 20:29
  • References with the & notation are a C++ feature, I it is strict C you ca'nt use them. The fact here is, the pointer cease to exist after the function, but the caller receives it's value in another variable, which is enough. – Elvis Teixeira Apr 05 '17 at 21:10