Hi Guys,
I was having a little trouble with dynamic memory allocation. Can anyone please tell me what is the purpose of dynamically allocating a single variables, like this:
Can anyone please tell me what is the purpose of dynamically allocating a single variables
A dynamic variable really does not have any big advantage over regular variable's except the fact that you are able to delete them in case you want to free some ram(I am not even sure if that a legitimate thought).
Can anyone please tell me what is the purpose of dynamically allocating a single variables
DMA (Dynamic Memory Allocation) is the process of allocating memory from the heap (RAM), and not the stack.
Basic types, such as int, char, and float, don't require memory from the heap, but instead, they should be placed on the stack (automatic variables). Large structures, or types, should be placed on the heap.
As Framework says, you have a small amount of stack space. Huge allocations (like very big arrays) have to be allocated dynamically as they simply cannot fit in the stack.
Factors was on the right track; you have to delete them yourself, but the key point there is that they keep existing until you do that yourself.
This function is broken:
1 2 3 4 5
int* returnArray()
{
int array[5];
return array;
}
because the 5 int values will be written over once the function ends.
The only way of making a dynamically allocated variables hat can be accessed outside the scope is by making it a global dynamically allocated variable. That's why cire is right with.
1 2 3 4 5 6 7 8 9
{
int * ptr ;
{
*ptr = 7 ;
// do stuff with ptr
}
delete ptr ;
}