Search code examples
c++structheap-memoryassignstack-memory

c++ assigning only part of struct returned by function call


I have the following struct:

struct foo{
    int a[4];
    int b[4];
}

I have the following function:

foo get_foo()
{
    foo ret_val;
    <..some assignments here..>
    return ret_val;
}

Now, my main code:

void* process_a()
{
    int* pa = get_foo().a;
    <..do smth with "pa"..>
     return pa;
 }

It appears that the code is running fine, but it is completely unknown what happens with complete structure, since I have access only to subpart of it. And, the questions:

  • is it fine to assign to a pointer only a part of the structure created on stack?
  • where is the foo structure? on stack? or heap?
  • Is compiler smart enough to allocate only int[4] (which is quite unlikely) or it will alloc the complete foo?
  • what is the time to live for my pa? Can I reliably use that pointer outside the process_a() function?

Thanks! Igor.


Solution

    • Yes, but it is only valid during the structure's lifetime.
    • The structure returned from the function is a temporary object, and it gets destroyed immediately.
      There will be some space, probably "on the stack", for the function to return its result into.
      Once the right hand side of the assignment has executed, the structure is not stored anywhere, because it doesn't exist.
    • It will almost certainly allocate space for an entire structure.
    • The lifetime of pa is the body of process_a, but the lifetime of *pa has expired as explained above.
      Because of this, you can't use the value of pa for anything (except copying it) even inside process_a.

    Your code appears to be running fine because "appears to be running fine" is a valid form of undefined behaviour, like anything and everything else.