1

I had to return pointer of a structure object in function but I didn't store them as pointers, so I used return &myStructObject; to return. It does not give any compile-time error but what i'm trying to do is correct?

Firat Akandere
  • 523
  • 2
  • 12

3 Answers3

1

If the struct variable whose pointer you want to return is still in scope after returning from the function, what you are doing is correct.

On the other hand, if the struct variable in question is local to the function and will be destroyed (freed) once you return from the function, then the pointer you will return will be a dangling pointer, and will not serve your purpose.

EDIT:

By "will not serve your purpose", I mean it will not do what you think it will! There's no point discussing what harms it can do, when you are sure it doesn't do what you expect it to do!

CinCout
  • 9,486
  • 12
  • 49
  • 67
  • Please elaborate on "will not serve your purpose" to make clear how unpredictable and dangerous it really is. This link might help do so: https://stackoverflow.com/q/2397984 – Deduplicator Nov 04 '14 at 15:56
0

If structure object you are referring to is local to the function then you should not return the address of that struct object. This is because when your function returns call to its caller then all local variables are destroyed from memory.

For e.g:-

Below is a fatal error

int* myFunc ()
{
  int p = 4;            // memory is allocated for p.
  // do something.
  return &p;            // memory for p is deallocated and you are returning pointer to that memory 
}
ravi
  • 10,994
  • 1
  • 18
  • 36
-1

If you have got something local in a function and you are returning address to that, it will be lost i.e. nullified. The reason is that the function you are returning the address from will be POPped from the stack and anything non-static (non-global) will be lost. In essence, anything that the programme memory hasn't got as a "lifelong" resource will be gone. You can pass pointers as an argument to the function and dereference it to modify value pointed by the pointer. But anything that is non-static (or non-global) and returned as an address will cause you access violation-type errors.

ha9u63a7
  • 6,233
  • 16
  • 73
  • 108
  • 1
    You didn't explain what I mentioned in the answer. You simply malloced and freed memory and then tried to access the memory. What did I say in my answer? It is about leaving the scope and leaving the stack. – ha9u63a7 Nov 04 '14 at 20:23