Stack Vs Heap C++

vickyrare

vickyrare
Apr 21, 2009
103
0
21
Karachi
Stack Vs Heap

Stack:
When you write simple programs in C and C++, you don't care where the memory for your variables are allocated, as by default they all ended up on Stack.

The stack is where memory is allocated for automatic variables within functions. A stack is a Last In First Out (LIFO) storage device where new storage is allocated and deallocated at only one ``end'', called the Top of the stack.

Example program;

Code:
#include <iostream.h>
using namespace std;
void myFunction()
{
    int myArray[10] = {1,2,3,4,5,6,7,8,9,10};
    for(int i = 0; i < 10; i++)
        cout<<<<myArray[i]<<endl;

}
int main()
{
    myFunction();
    return 0;
}
In the program, shown above the scope of array myArray is limited to enclosing braces {}, once we return from myFunction, the scope of myArray ends, which will cleaned up and in the main function there is no way to access myArray anymore.

There are couple of problems in the program which used allocations on Stack.
First you can't access the memory once we reached the scope brace.
Second you have to know in advance how much memory will be needed, which is sometimes hard to predict.
Third there is a certain limit on how much can be allocated on Stack, memory allocations on Heap also suffer from this problem, but in the case of Stack the limit is too low.

The memory allocated on Stack is also called Static Memory Allocation.

Heap:
When a variable is defined in the source program, the type of the variable determines how much memory the compiler allocates. When the program executes, the variable consumes this amount of memory regardless of whether the program actually uses the memory allocated. This is particularly true for arrays. However, in many problems, it is not clear at the outset how much memory the program will actually need. Up to now, we have declared arrays to be ``large enough'' to hold the maximum number of elements we expect our application to handle. If too much memory is allocated and then not used, there is a waste of memory. If not enough memory is allocated, the program is not able to handle the input data.

We can make our program more flexible if, during execution, it could allocate additional memory when needed and free memory when not needed. Allocation of memory during execution is called dynamic memory allocation. C provides library functions to allocate and free memory dynamically during program execution. Dynamic memory is allocated on the heap by the system.
It is important to realize that dynamic memory allocation also has limits. If memory is repeatedly allocated, eventually the system will run out of memory.

Look at another example which uses memory allocated on heap.

Code:
#include <iostream.h>
using namespace std;
int* myFunction()
{
    int *myArray = malloc(10 * sizeof(int));
    for(int i = 0; i < 10; i++)
        cout<<<<myArray[i]<<endl;
    return myArray;

}
int main()
{
    int *array = myFunction();
    //in this case the array allocated in myFunction is available here.
    return 0;
}
There is one big problem using Heap, which is once you have allocated memory on Heap, now its your responsibility to free that memory once you are done with it.

In the program above we definitely leaked 4 bytes of memory. This is not a problem for small programs but once you started to write complicated programs then it can become a big problem.

The following program frees the memory once the user is done with the allocated memory.

Code:
#include <iostream.h>
using namespace std;
int* myFunction()
{
    int *myArray = malloc(10 * sizeof(int));
    for(int i = 0; i < 10; i++)
        cout<<<<myArray[i]<<endl;
    return myArray;

}
int main()
{
    int *array = myFunction();
    //in this case the array allocated in myFunction is available here.
    free(array);
    return 0;
}
C programmers use malloc to allocate memory and free to deallocate memory
C++ programmers use new to allocated memory and delete to deallocate memory.

Be careful malloc is incompatible with delete, same is true for new which is incompatible with free. Always use free to deallocate memory allocated using malloc.
Always use delete to deallocate memory allocated using new.

Hope some people will find this small tutorial useful.

http://ee.hawaii.edu/~tep/EE160/Book/chap1...ion2.1.1.8.html
 
Last edited:

Cade2

Talented
Feb 1, 2009
71
0
11
cade.mooo.com
There is significantly more to memory allocation in C++, including (but not limited to) smart pointers, using alloca to get the CRT to allocate on the stack, etc. Also, a very important difference between new/delete and malloc/free is that new and delete call constructors and destructors, but malloc and free do not. If you wish to explain memory allocation, please do not just copy and paste very basic C++ tutorials.

Also, to check for memory leaks, here's a (relatively) simple memory leak detector I wrote:
http://cade.mooo.com/pages/memleak.html
When the program is exited (the static destructor for MemReport is called), it'll print a report to the debugger of currently allocated memory blocks which were not freed, and their source. This tracker will only track leaks made with the macro'd new, so it wont detect leaks outside tracked code.
 
Last edited:

vickyrare

vickyrare
Apr 21, 2009
103
0
21
Karachi
Thanks for adding more info about memory allocation. I was trying to keep the thread simple as too much information tends to confuse people. I have looked at the leak detector you have mentioned. It's pretty simple and self explanatory. BTW smart pointer is the best way to manage memory on heap, as you don't have to deallocate memory by hand.
 

Rapchik Killer

Well-known member
Jan 18, 2007
1,263
0
41
34
Karachi, Pakistan
@vick: nice tutorial bro..

@cade: its targeted for noob so i dont think it would be wise to discuss smart pointers or even bsts here.. btw for mem allocation i prefer using ned malloc.. its fast and ultra portable..
 

shujaswati

Pen Tester / Security Analyst
May 7, 2008
3,269
0
41
KSA / PSH / ISL
www.about.me
The topic related to Data structure memory allocation technique, Right? Well there are others too like linked list, queue, trees, graphs, stack and the allocation types like sequential and linear. Btw, nice share.
 

Cade2

Talented
Feb 1, 2009
71
0
11
cade.mooo.com
Thanks for the recommendation, Rapchik. I use my own memory allocator, for a bunch of reasons like allocation reports and such. One of the main plus points about it is that it has a block allocator, where I can get multiple small blocks of memory from larger pre-allocated blocks. Very fast, and I've had to use it on consoles too. :)
 
General chit-chat
Help Users
We have disabled traderscore and are working on a fix. There was a bug with the plugin | Click for Discord
  • No one is chatting at the moment.
    NaNoW NaNoW: ....