El Pinguino
El Pinguino

Reputation: 31

What happens to a dynamic array (on the heap) within a struct on the stack?

My concern is whether or not the array should be deallocated. Here is an example:

typedef struct
{
    int *values;
    int length;
} a_struct;

void foo()
{
    a_struct myStruct;
    myStruct.values = new int[NUM];  

    delete[] myStruct.values; // Is this needed?
    return;  
}

My understanding is that myStruct (which is on the stack) will get deleted automatically upon the "return" statement. Does it delete "values" as well?

Upvotes: 0

Views: 152

Answers (4)

user207421
user207421

Reputation: 310980

Nothing gets 'deleted'. The stack is popped. Period. As the struct doesn't have a destructor, nothing else happens.

Upvotes: 0

cristicbz
cristicbz

Reputation: 431

Yes it is needed, the struct only stores the address of the array. These days people would just store a std::vector<> (or if you just want an owning pointer to something a std::unique_ptr<>).

Upvotes: 0

Matteo Italia
Matteo Italia

Reputation: 126867

It does deallocate the pointer values, but not what it points to - after all, what does a_struct know about what you assigned to that pointer? Maybe it's a pointer to stuff allocated on the stack, or to an array shared with another struct.

So, yes, you need to manually deallocate it (although in modern C++ often "smart pointers" are used to manage memory).

Upvotes: 4

user529758
user529758

Reputation:

No, it doesn't, you should delete it manually. myStruct going out of scope (and thus the myStruct.values member, i. e. the pointer being invalidated) has nothing to do with the dynamically allocated memory. The golden rule: if you call new[], always delete[] (same for new and delete).

Upvotes: 2

Related Questions