You are on page 1of 11

Stack & Heap Memory

Stack & Heap memory

Variables in a C++ (or Qt) program are


allocated on stack or heap memory

Stack : Examples
int
i = 10;
primitive data type
QDate d(2000,1,1);
Qt Object
Fraction f;
Object of a user-defined class (Ezust
chapter 2)

Heap : Examples
int*
i = new int(10);
primitive data type
QDate* d = new QDate(2000,1,1);
Qt Object
Fraction* f = new Fraction();
Object of a user-defined class (Ezust
chapter 2)

Difference between Stack & Heap memory


Stack memory is managed for you.
You need not worry about the
allocation and de-allocation of this
memory.
Heap memory should be managed by
the programmer. You need to allocate
(new) and de-allocate (delete) the
heap memory.

Golden rule of memory management in C++

If you have allocated memory using the


keyword new, then you have to explicitly
delete the memory (using delete) when
the data in the memory is no longer
needed in your program.

Improper Memory Management: Memory Leaks

Memory leak : Heap memory is


allocated by the program but it loses
track of this memory so that becomes
inaccessible to the program

Memory Leak: Example


Fraction* f1 = new Fraction();
f1 = new Fraction();
Heap

f1
m_Numerator =0
m_Denominator =0

m_Numerator =0
m_Denominator =0

Inaccessible
memory memory leak

To Avoid Memory Leak: Example


Fraction* f1 = new Fraction();
delete f1;
f1 = new Fraction();
Heap

f1
m_Numerator =0
m_Denominator =0

m_Numerator =0
m_Denominator =0

Summary
This presentation
explained the difference between
stack & heap memory
demonstrated the importance of
memory management

Way Forward..
Make sure you understand the contents
of this presentation before you look at
the presentation titled Qts Child
Management Facility

You might also like