SlideShare a Scribd company logo
1 of 5
Question
Sir,
I have following questions in C++
1.What is Stack and heap ? What is the use (2 separate) of it?
2.When i declare a global object where it is kept? Stack or heap? How compiler knows about
that? Only with new operator?
Answer
1.What is Stack and heap ? What is the use (2 separate) of it?
------------------------------------------------------------------------
The stack and heap are two separate memory areas used for data storage in main memory in a
C++ program.
Stack storage is automatically managed by the code and is used for data local to a function
call - note I say function call not function. Note that C/C++ call this automatic storage. The
stack works by allocating a new block of storage for each function call and relinquishing this
storage on function return. Processors usually have support for managing stack data - usually
in the form of specific registers to point to current stack top (and maybe a base pointer to the
whole stack frame for a function call) and instructions to push and pop data on and off of the
stack.
The stack is so named because of the data structure it uses - a stack or LIFO (last in first out).
Stacks are allocated on a per thread of execution basis and are fundamental to most if not all
implementations of threads, tasks and other types of units of execution.Operating systems
often have a separate kernel mode stack they use internally.
Although the operation of the stack has dynamic properties the compiler has enough
information to calculate what storage is required by each function call, and so has static
properties as well. Hence I suppose the term automatic rather than dynamic to prevent
confusion with fully dynamic storage.
A heap on the other hand is an area where the programmer has to manually manage allocation
and deallocation of storage by making specific allocation and deallocation requests (new and
delete in C++) and is used for dynamic storage (i.e. storage requested at runtime). The
memory used by a heap is usually obtained directly from the operating system, although
C/C++ runtime libraries may try to improve performance by requesting big blocks from the
operating system and dividing them up for small allocations. The heap is sometimes called
the free store in C and C++.
Note that heap is also a data structure. However whether a free store is really implemented as
a heap structure is an implementation issue.
2.When i declare a global object where it is kept? Stack or heap?
------------------------------------------------------------------------------------
Neither.
Such data is stored in the static storage area. Static storage is fixed for the whole program
duration. The compiler and linker have enough information to calculate the required storage
requirements at program build time and this is mapped into memory at program load time -
often directly from the executable file. Hence static objects exist for the whole duration of the
program - although those requiring complex (i.e. dynamic) initialisation will not be initialised
until some specific point in the program execution. Simple static initialisation (e.g.
initialising a static int to some value such as 123) can be done at build time and this value just
copied from the executable file into memory at program startup.
2a/ How compiler knows about that? Only with new operator?
-------------------------------------------------------------------
i) In a function definition static storage is requested using the static keyword. Otherwise an
object has automatic (stack) storage. Unlike local automatic objects, local static objects' state
survives across function calls but a local static object cannot be accessed outside of the
function (or smaller) scope in which it is defined.
ii) Outside of any function definition _any_ object definition defines an object having static
storage.
If such a definition is prefixed with the static keyword then it is private to the source file in
which it is defined (or more accurately to the translation unit in which it is defined. A
translation unit is approximately what is compiled by the compiler proper after
preprocessing). Such private static objects are only visible to code following their definition
until the end of the file. Such private static objects are said to have internal linkage.
If such a definition is not prefixed with the static keyword then it has external linkage and is
visible as a symbol to the linker, and therefore to other source files (translation units). Such
objects _must_ obey the one definition rule across the whole program and not just within the
source code file (translation unit) in which they are defined. Only _one_ translation unit can
define (i.e. cause storage to be reserved for) an external static object. All other uses must use
a declaration by using the extern keyword before the type and name of the global object.
So to summarise:
C and C++ have three types of storage:
1/ Static storage for function-local and internal and external global objects that have storage
allocated for the whole of the program duration. Complex static objects requiring dynamic
initialisation may not be fully initialised (created) until some later point (if at all) in a
programs execution - but once fully created they exist until destroyed during program
termination.
2/ Automatic storage on the stack. Such objects apply only to objects defined locally to a
function. They exist until the function returns or for a shorter time if they have a smaller
scope within the function. Automatic storage is the default storage class for local function
objects.
Stacks are allocated on a per unit of execution basis.
3/ Dynamic storage on the free store or heap is managed at runtime (i.e. dynamically) via
explicit calls or operators - e.g. new and delete. Objects allocated from the free store exist
until explicitly released (freed, deleted, deallocated, etc...).
In addition:
4/ The terms static and dynamic when used in the context of C++ programs often mean "at
compile / link time" (static) and "at run time" (dynamic).
5/ A function or object (variable) definition reserves storage for that entity. A declaration
merely states that such an entity exists. Such entities can only be _defined_ once in a
program. However they can be declared to exist as many times as required. A function
declaration is sometimes called a function prototype (from C). Most definitions in C and C++
are also declarations. Only global objects with external linkage can have declarations in C
and C++, all other such statements are definitions (and declarations).
Examples:
---------
extern int GlobalInt; // declaration of a static 'global' object defined elsewhere
int GlobalInt = 12; // definition of a static 'global' object having external linkage
static int PrivateStatic = 10; // definition of a static 'global' object having internal linkage
void SomeFunction // function declaration or prototype; function defined
elsewhere
( int n
, long & value
);
void SomeFunction // function definition:
( int n
, long & value // arguments are stack based having automatic storage
)
{
if ( 0==n ) // n for this call different from n of other calls
{
return;
}
static int callDepth(0); // Define static local variable. Only created once.
// State (value) of callDepth survives across function calls.
++callDepth;
std::cout << "At call depth: "
<< callDepth
<< 'n'
;
long newValue = value * n; // Define automatic object stored on function call stack
frame
SomeFunction( n-1, newValue ); // Recursive function call, gets a new stack frame
value = newValue;
--callDepth;
} // n, value, newValue for this call destroyed here;
// callDepth static so continues to exist with its current state
int main()
{
long * pValue = new long; // Dynamically create a new long object on the free store at
// runtime and return a pointer to it. Note the created object
// is default constructed in this case, which for built in types
// equates to being uninitialised.
*pValue = 1;
SomeFunction(10, *pValue);
std::cout << "Result of SomeFunction(10, 1) is " << *pValue << std::endl;
delete pValue; // Objects dynamically created exist until explicitly deleted.
// Note in this case we could probably get away with forgetting
// to delete the object pointed to by pValue as the next
// operation is to terminate the program execution and most
// modern desktop and server operating systems will be able to
// release all such process resources. However this is not true
// in the general case even for dynamically allocated objects
// that should be deleted as here just before program
// termination. Some resources held by such objects (of user
// defined types) may not be automatically released on program
// termination and some execution environments (e.g. embedded
// environments) may not do clean up for us.
}
// Static objects notionally destroyed here: after or during
// return from main but before program termination.
// This includes PrivateStatic, GlobalInt and callDepth
Hope this is of use and please ask further questions to clarify anything you do not understand
as trying to take all this in at once could be a bit overwhelming and I do not know what you
do or do not know already. Hopefully this will at least act as a starting point for your
enlightenment of this subject and something we can both refer to if you require further help.

More Related Content

What's hot

[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...Francesco Casalegno
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1Teksify
 
Writing Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel SchulhofWriting Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel SchulhofWithTheBest
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overviewgourav kottawar
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design PatternsStefano Fago
 
C++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect ForwardingC++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect ForwardingFrancesco Casalegno
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Sergey Platonov
 
friends functionToshu
friends functionToshufriends functionToshu
friends functionToshuSidd Singh
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.Russell Childs
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answerssheibansari
 
STL ALGORITHMS
STL ALGORITHMSSTL ALGORITHMS
STL ALGORITHMSfawzmasood
 
Алексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляАлексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляSergey Platonov
 

What's hot (20)

C++11 Multithreading - Futures
C++11 Multithreading - FuturesC++11 Multithreading - Futures
C++11 Multithreading - Futures
 
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
[C++] The Curiously Recurring Template Pattern: Static Polymorphsim and Expre...
 
C++11
C++11C++11
C++11
 
data Structure Lecture 1
data Structure Lecture 1data Structure Lecture 1
data Structure Lecture 1
 
Writing Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel SchulhofWriting Node.js Bindings - General Principles - Gabriel Schulhof
Writing Node.js Bindings - General Principles - Gabriel Schulhof
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
 
The Style of C++ 11
The Style of C++ 11The Style of C++ 11
The Style of C++ 11
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
 
Link list
Link listLink list
Link list
 
C++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect ForwardingC++11: Rvalue References, Move Semantics, Perfect Forwarding
C++11: Rvalue References, Move Semantics, Perfect Forwarding
 
What's New in C++ 11?
What's New in C++ 11?What's New in C++ 11?
What's New in C++ 11?
 
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
Александр Гранин, Функциональная 'Жизнь': параллельные клеточные автоматы и к...
 
The STL
The STLThe STL
The STL
 
friends functionToshu
friends functionToshufriends functionToshu
friends functionToshu
 
Recursion to iteration automation.
Recursion to iteration automation.Recursion to iteration automation.
Recursion to iteration automation.
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
 
STL ALGORITHMS
STL ALGORITHMSSTL ALGORITHMS
STL ALGORITHMS
 
C++11
C++11C++11
C++11
 
Алексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуляАлексей Кутумов, Вектор с нуля
Алексей Кутумов, Вектор с нуля
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 

Viewers also liked

45ος διεθνής διαγωνισμός αλληλογραφίας νέων 2016
45ος διεθνής διαγωνισμός αλληλογραφίας νέων 201645ος διεθνής διαγωνισμός αλληλογραφίας νέων 2016
45ος διεθνής διαγωνισμός αλληλογραφίας νέων 20164Gym Glyfadas
 
Android operating system
Android operating systemAndroid operating system
Android operating systemShahid Sayed
 
Трудове навчання 6 клас Сидоренко 2014 (для хлопців) от Freegdz.com
Трудове навчання 6 клас Сидоренко 2014 (для хлопців) от Freegdz.comТрудове навчання 6 клас Сидоренко 2014 (для хлопців) от Freegdz.com
Трудове навчання 6 клас Сидоренко 2014 (для хлопців) от Freegdz.comfreegdz
 
wilder_vita_2016_links
wilder_vita_2016_linkswilder_vita_2016_links
wilder_vita_2016_linksMichael Wilder
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3Mahmoud Alfarra
 
Biologiya 9-klas-matyash-shabatura-2009
Biologiya 9-klas-matyash-shabatura-2009Biologiya 9-klas-matyash-shabatura-2009
Biologiya 9-klas-matyash-shabatura-2009freegdz
 
C++ memory leak detection
C++ memory leak detectionC++ memory leak detection
C++ memory leak detectionVõ Hòa
 
Java and SOA for beginners
Java and SOA for beginnersJava and SOA for beginners
Java and SOA for beginnersEdureka!
 
Evaluation Q4
Evaluation Q4Evaluation Q4
Evaluation Q4mag_anna
 
number system full discription in bangla
number system full discription in banglanumber system full discription in bangla
number system full discription in banglaarnab73
 

Viewers also liked (14)

45ος διεθνής διαγωνισμός αλληλογραφίας νέων 2016
45ος διεθνής διαγωνισμός αλληλογραφίας νέων 201645ος διεθνής διαγωνισμός αλληλογραφίας νέων 2016
45ος διεθνής διαγωνισμός αλληλογραφίας νέων 2016
 
Emails week 3
Emails week 3Emails week 3
Emails week 3
 
Android operating system
Android operating systemAndroid operating system
Android operating system
 
Трудове навчання 6 клас Сидоренко 2014 (для хлопців) от Freegdz.com
Трудове навчання 6 клас Сидоренко 2014 (для хлопців) от Freegdz.comТрудове навчання 6 клас Сидоренко 2014 (для хлопців) от Freegdz.com
Трудове навчання 6 клас Сидоренко 2014 (для хлопців) от Freegdz.com
 
Media evaluation question 2
Media evaluation question 2Media evaluation question 2
Media evaluation question 2
 
Java
JavaJava
Java
 
wilder_vita_2016_links
wilder_vita_2016_linkswilder_vita_2016_links
wilder_vita_2016_links
 
‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3‫Object Oriented Programming_Lecture 3
‫Object Oriented Programming_Lecture 3
 
Biologiya 9-klas-matyash-shabatura-2009
Biologiya 9-klas-matyash-shabatura-2009Biologiya 9-klas-matyash-shabatura-2009
Biologiya 9-klas-matyash-shabatura-2009
 
C++ memory leak detection
C++ memory leak detectionC++ memory leak detection
C++ memory leak detection
 
Java and SOA for beginners
Java and SOA for beginnersJava and SOA for beginners
Java and SOA for beginners
 
Brexit aula 1.
Brexit   aula 1.Brexit   aula 1.
Brexit aula 1.
 
Evaluation Q4
Evaluation Q4Evaluation Q4
Evaluation Q4
 
number system full discription in bangla
number system full discription in banglanumber system full discription in bangla
number system full discription in bangla
 

Similar to Memory management in c++

Data structure week 1
Data structure week 1Data structure week 1
Data structure week 1karmuhtam
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1ReKruiTIn.com
 
Storage Class Specifiers in C++
Storage Class Specifiers in C++Storage Class Specifiers in C++
Storage Class Specifiers in C++Reddhi Basu
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And AnswerJagan Mohan Bishoyi
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answerlavparmar007
 
ARM Embeded_Firmware.pdf
ARM Embeded_Firmware.pdfARM Embeded_Firmware.pdf
ARM Embeded_Firmware.pdfhakilic1
 
Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2ppd1961
 
Memory Allocation & Direct Memory Allocation in C & C++ Language PPT
Memory Allocation & Direct Memory Allocation in C & C++ Language PPTMemory Allocation & Direct Memory Allocation in C & C++ Language PPT
Memory Allocation & Direct Memory Allocation in C & C++ Language PPTAkhilMishra50
 
What is storage class
What is storage classWhat is storage class
What is storage classIsha Aggarwal
 
CJPCCS BCA VISNAGAR functions in C language
CJPCCS BCA VISNAGAR  functions in C languageCJPCCS BCA VISNAGAR  functions in C language
CJPCCS BCA VISNAGAR functions in C languageFCSCJCS
 
Buffer overflow tutorial
Buffer overflow tutorialBuffer overflow tutorial
Buffer overflow tutorialhughpearse
 
(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_types(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_typesNico Ludwig
 
Static Keyword Static is a keyword in C++ used to give special chara.pdf
  Static Keyword Static is a keyword in C++ used to give special chara.pdf  Static Keyword Static is a keyword in C++ used to give special chara.pdf
Static Keyword Static is a keyword in C++ used to give special chara.pdfKUNALHARCHANDANI1
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)rashmita_mishra
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory ManagementRahul Jamwal
 
Let's Talk Locks!
Let's Talk Locks!Let's Talk Locks!
Let's Talk Locks!C4Media
 

Similar to Memory management in c++ (20)

Data structure week 1
Data structure week 1Data structure week 1
Data structure week 1
 
C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1C, C++ Interview Questions Part - 1
C, C++ Interview Questions Part - 1
 
Storage Class Specifiers in C++
Storage Class Specifiers in C++Storage Class Specifiers in C++
Storage Class Specifiers in C++
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
Readme
ReadmeReadme
Readme
 
ARM Embeded_Firmware.pdf
ARM Embeded_Firmware.pdfARM Embeded_Firmware.pdf
ARM Embeded_Firmware.pdf
 
Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2Handling Exceptions In C &amp; C++ [Part B] Ver 2
Handling Exceptions In C &amp; C++ [Part B] Ver 2
 
C++ development within OOo
C++ development within OOoC++ development within OOo
C++ development within OOo
 
Memory Allocation & Direct Memory Allocation in C & C++ Language PPT
Memory Allocation & Direct Memory Allocation in C & C++ Language PPTMemory Allocation & Direct Memory Allocation in C & C++ Language PPT
Memory Allocation & Direct Memory Allocation in C & C++ Language PPT
 
What is storage class
What is storage classWhat is storage class
What is storage class
 
CJPCCS BCA VISNAGAR functions in C language
CJPCCS BCA VISNAGAR  functions in C languageCJPCCS BCA VISNAGAR  functions in C language
CJPCCS BCA VISNAGAR functions in C language
 
Buffer overflow tutorial
Buffer overflow tutorialBuffer overflow tutorial
Buffer overflow tutorial
 
(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_types(3) cpp abstractions more_on_user_defined_types
(3) cpp abstractions more_on_user_defined_types
 
Static Keyword Static is a keyword in C++ used to give special chara.pdf
  Static Keyword Static is a keyword in C++ used to give special chara.pdf  Static Keyword Static is a keyword in C++ used to give special chara.pdf
Static Keyword Static is a keyword in C++ used to give special chara.pdf
 
New microsoft office word document (2)
New microsoft office word document (2)New microsoft office word document (2)
New microsoft office word document (2)
 
Functions
FunctionsFunctions
Functions
 
C++ Memory Management
C++ Memory ManagementC++ Memory Management
C++ Memory Management
 
Let's Talk Locks!
Let's Talk Locks!Let's Talk Locks!
Let's Talk Locks!
 
C++ Version 2
C++  Version 2C++  Version 2
C++ Version 2
 

Recently uploaded

Internet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxInternet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxVelmuruganTECE
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleAlluxio, Inc.
 
home automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadhome automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadaditya806802
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating SystemRashmi Bhat
 
11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdfHafizMudaserAhmad
 
"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...Erbil Polytechnic University
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Crushers to screens in aggregate production
Crushers to screens in aggregate productionCrushers to screens in aggregate production
Crushers to screens in aggregate productionChinnuNinan
 
multiple access in wireless communication
multiple access in wireless communicationmultiple access in wireless communication
multiple access in wireless communicationpanditadesh123
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfRajuKanojiya4
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the weldingMuhammadUzairLiaqat
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm Systemirfanmechengr
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionMebane Rash
 
Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptMadan Karki
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 
Autonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.pptAutonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.pptbibisarnayak0
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substationstephanwindworld
 

Recently uploaded (20)

Internet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptxInternet of things -Arshdeep Bahga .pptx
Internet of things -Arshdeep Bahga .pptx
 
Correctly Loading Incremental Data at Scale
Correctly Loading Incremental Data at ScaleCorrectly Loading Incremental Data at Scale
Correctly Loading Incremental Data at Scale
 
home automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadhome automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasad
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating System
 
11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf
 
"Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ..."Exploring the Essential Functions and Design Considerations of Spillways in ...
"Exploring the Essential Functions and Design Considerations of Spillways in ...
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Crushers to screens in aggregate production
Crushers to screens in aggregate productionCrushers to screens in aggregate production
Crushers to screens in aggregate production
 
multiple access in wireless communication
multiple access in wireless communicationmultiple access in wireless communication
multiple access in wireless communication
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdf
 
Designing pile caps according to ACI 318-19.pptx
Designing pile caps according to ACI 318-19.pptxDesigning pile caps according to ACI 318-19.pptx
Designing pile caps according to ACI 318-19.pptx
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the welding
 
Class 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm SystemClass 1 | NFPA 72 | Overview Fire Alarm System
Class 1 | NFPA 72 | Overview Fire Alarm System
 
US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of Action
 
Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.ppt
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 
Autonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.pptAutonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.ppt
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substation
 

Memory management in c++

  • 1. Question Sir, I have following questions in C++ 1.What is Stack and heap ? What is the use (2 separate) of it? 2.When i declare a global object where it is kept? Stack or heap? How compiler knows about that? Only with new operator? Answer 1.What is Stack and heap ? What is the use (2 separate) of it? ------------------------------------------------------------------------ The stack and heap are two separate memory areas used for data storage in main memory in a C++ program. Stack storage is automatically managed by the code and is used for data local to a function call - note I say function call not function. Note that C/C++ call this automatic storage. The stack works by allocating a new block of storage for each function call and relinquishing this storage on function return. Processors usually have support for managing stack data - usually in the form of specific registers to point to current stack top (and maybe a base pointer to the whole stack frame for a function call) and instructions to push and pop data on and off of the stack. The stack is so named because of the data structure it uses - a stack or LIFO (last in first out). Stacks are allocated on a per thread of execution basis and are fundamental to most if not all implementations of threads, tasks and other types of units of execution.Operating systems often have a separate kernel mode stack they use internally. Although the operation of the stack has dynamic properties the compiler has enough information to calculate what storage is required by each function call, and so has static properties as well. Hence I suppose the term automatic rather than dynamic to prevent confusion with fully dynamic storage. A heap on the other hand is an area where the programmer has to manually manage allocation and deallocation of storage by making specific allocation and deallocation requests (new and delete in C++) and is used for dynamic storage (i.e. storage requested at runtime). The memory used by a heap is usually obtained directly from the operating system, although C/C++ runtime libraries may try to improve performance by requesting big blocks from the operating system and dividing them up for small allocations. The heap is sometimes called the free store in C and C++. Note that heap is also a data structure. However whether a free store is really implemented as a heap structure is an implementation issue. 2.When i declare a global object where it is kept? Stack or heap?
  • 2. ------------------------------------------------------------------------------------ Neither. Such data is stored in the static storage area. Static storage is fixed for the whole program duration. The compiler and linker have enough information to calculate the required storage requirements at program build time and this is mapped into memory at program load time - often directly from the executable file. Hence static objects exist for the whole duration of the program - although those requiring complex (i.e. dynamic) initialisation will not be initialised until some specific point in the program execution. Simple static initialisation (e.g. initialising a static int to some value such as 123) can be done at build time and this value just copied from the executable file into memory at program startup. 2a/ How compiler knows about that? Only with new operator? ------------------------------------------------------------------- i) In a function definition static storage is requested using the static keyword. Otherwise an object has automatic (stack) storage. Unlike local automatic objects, local static objects' state survives across function calls but a local static object cannot be accessed outside of the function (or smaller) scope in which it is defined. ii) Outside of any function definition _any_ object definition defines an object having static storage. If such a definition is prefixed with the static keyword then it is private to the source file in which it is defined (or more accurately to the translation unit in which it is defined. A translation unit is approximately what is compiled by the compiler proper after preprocessing). Such private static objects are only visible to code following their definition until the end of the file. Such private static objects are said to have internal linkage. If such a definition is not prefixed with the static keyword then it has external linkage and is visible as a symbol to the linker, and therefore to other source files (translation units). Such objects _must_ obey the one definition rule across the whole program and not just within the source code file (translation unit) in which they are defined. Only _one_ translation unit can define (i.e. cause storage to be reserved for) an external static object. All other uses must use a declaration by using the extern keyword before the type and name of the global object. So to summarise: C and C++ have three types of storage: 1/ Static storage for function-local and internal and external global objects that have storage allocated for the whole of the program duration. Complex static objects requiring dynamic initialisation may not be fully initialised (created) until some later point (if at all) in a programs execution - but once fully created they exist until destroyed during program
  • 3. termination. 2/ Automatic storage on the stack. Such objects apply only to objects defined locally to a function. They exist until the function returns or for a shorter time if they have a smaller scope within the function. Automatic storage is the default storage class for local function objects. Stacks are allocated on a per unit of execution basis. 3/ Dynamic storage on the free store or heap is managed at runtime (i.e. dynamically) via explicit calls or operators - e.g. new and delete. Objects allocated from the free store exist until explicitly released (freed, deleted, deallocated, etc...). In addition: 4/ The terms static and dynamic when used in the context of C++ programs often mean "at compile / link time" (static) and "at run time" (dynamic). 5/ A function or object (variable) definition reserves storage for that entity. A declaration merely states that such an entity exists. Such entities can only be _defined_ once in a program. However they can be declared to exist as many times as required. A function declaration is sometimes called a function prototype (from C). Most definitions in C and C++ are also declarations. Only global objects with external linkage can have declarations in C and C++, all other such statements are definitions (and declarations). Examples: --------- extern int GlobalInt; // declaration of a static 'global' object defined elsewhere int GlobalInt = 12; // definition of a static 'global' object having external linkage static int PrivateStatic = 10; // definition of a static 'global' object having internal linkage void SomeFunction // function declaration or prototype; function defined elsewhere ( int n , long & value ); void SomeFunction // function definition: ( int n , long & value // arguments are stack based having automatic storage )
  • 4. { if ( 0==n ) // n for this call different from n of other calls { return; } static int callDepth(0); // Define static local variable. Only created once. // State (value) of callDepth survives across function calls. ++callDepth; std::cout << "At call depth: " << callDepth << 'n' ; long newValue = value * n; // Define automatic object stored on function call stack frame SomeFunction( n-1, newValue ); // Recursive function call, gets a new stack frame value = newValue; --callDepth; } // n, value, newValue for this call destroyed here; // callDepth static so continues to exist with its current state int main() { long * pValue = new long; // Dynamically create a new long object on the free store at // runtime and return a pointer to it. Note the created object // is default constructed in this case, which for built in types // equates to being uninitialised. *pValue = 1; SomeFunction(10, *pValue); std::cout << "Result of SomeFunction(10, 1) is " << *pValue << std::endl; delete pValue; // Objects dynamically created exist until explicitly deleted. // Note in this case we could probably get away with forgetting // to delete the object pointed to by pValue as the next // operation is to terminate the program execution and most // modern desktop and server operating systems will be able to // release all such process resources. However this is not true // in the general case even for dynamically allocated objects // that should be deleted as here just before program // termination. Some resources held by such objects (of user // defined types) may not be automatically released on program
  • 5. // termination and some execution environments (e.g. embedded // environments) may not do clean up for us. } // Static objects notionally destroyed here: after or during // return from main but before program termination. // This includes PrivateStatic, GlobalInt and callDepth Hope this is of use and please ask further questions to clarify anything you do not understand as trying to take all this in at once could be a bit overwhelming and I do not know what you do or do not know already. Hopefully this will at least act as a starting point for your enlightenment of this subject and something we can both refer to if you require further help.