Wednesday, June 27, 2018

c++ - Allocated memory is in the stack or heap



Im declaring a static vector, and allocating/contructing the object within a function (create). I want to know if the memory allocated was in the heap or in the stack. Im confused



// Example program
#include

#include

using namespace std;


typedef std::vector vector1Int;

static vector1Int hello;

void create(){

hello = vector1Int(8,12);
}

int main()
{

create();

return 0;
}


Answer



Possibly neither. The precise terms are




  • static storage: for data that exists as long as the process exists;

  • automatic storage: for data that is allocated and fred as the process enters/exits different scopes;

  • dynamic storage: for data that must be explicitly requested and exists until it is explicitly fred.




Usually automatic memory lives in the stack and dynamic storage lives in the heap. But the compiler is completely free to implement all those storage types in whatever way they want, as long as it respects the rules for lifespan.



So:



static vector1Int hello;


is in the file scope and creates an object of type vector1Int in static storage.



And this




hello = vector1Int(8,12);


will cause std::vector to create room for at least 8 integers. We can usually assume that this will be taken from dynamic storage. However, this is not a rule. For instance, you could easily make std::vector use static or automatic memory by implementing your own allocator (not general purpose memory allocator, but STL allocator).



When your program reaches the end of the main function, the destructor of std::vector will be called for hello, and any dynamic memory that hello had requested will be given back to the memory manager.



The memory for the object hello itself is not fred because it is static. Instead, it is given back to the OS together with anything else the process used when the process terminates.




Now, if hello had been declared as a local variable of create, then the destructor would be called at the end of that function. In that case, hello would have been allocated at automatic storage, and would be fred at the end of create.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...