Stores temporary variables created by each function with a LIFO data structure managed by CPU.
Example:
Entity entity("oleguer"); // Value based: Local to this function stack frame
std::cout << entity.GetName() << std::endl;
Example:
bool* visited = (bool*) alloca(sizeof(bool)*n); // alloca reserves in stack memory. WARNING! Not recommended, If causes stack overflow, program behavior is undefined
memset(visited, false, n); // ste memory to false
Pros:
Cons:
Example of dynamically allocated memory:
Entity *entity = new Entity("oleguer"); // Created in heap
std::cout << (*entity).GetName() << std::endl; // Access pointer value
std::cout << entity->GetName() << std::endl; // Arrow automatically does this for us
// As it is a pointer created in heap,
// here we could save the pointer and use it in another scope
some_entity_pointer = entity;
// This is not copying values, just setting another pointer
// When we are done with this variable,
// we have to free the memory allocated
delete entity;
// OBS: if we had assigned it to another pointer,
// we could have done: delete some_entity_pointer
// And would have deleted the same object
// (we can do this outside this scope)
Example:
bool* visited = (bool*) malloc(sizeof(bool)*n); // malloc reserves in heap memory.
memset(visited, false, n); // ste memory to false
Pros:
Cons:
OBS: The memory allocating part of new, is equivalent to malloc:
// Allocate memory and call constructor:
Entity* entity = new Entity();
// Allocate memory but don't call constructor
Entity* entity = (Entity*)malloc(sizeof(Entity));
OBS: If we create a new array, we must delete by delete[]:
int* array = new int[50];
destroy[] array;
OBS: std::vector allocates elems in heap:
vector<Type> vect; // Allocates header info, on the stack, but the elements heap
vector<Type> *vect = new vector<Type>; // Allocates everything in heap
// Elements are in the heap because they can change dynamically