If I define a variable inside the block of a control structure, does it exist only in the execution of that control structure’s block and not in the whole execution of the enclosing function?
also how can I monitor the exact memory usage of my programs and its changes (i.e.: changes in memory usage by creating and destroying variables)?
added later:
in following code I know v scope is if block, but I want to know whether v is created/destroyed in the memory at the start/end of the if block or at the start/end of the function func?
void func ()
{
if (true)
{
int v;//automatic storage class
v = 1;
}
}
It depends on where you declare the variable not define it.
The variable is only accessible in the scope where you declare it. It can be accessed beyond tht scope if you explicitly pass it around but if it remains valid would depend on the storage type of the variable.
For eg:
staticvariables remain alive throughout the program lifetime, while,returning address of an automatic variable from an function would result in Undefined Behavior because the variable does not remain valid after the function returns.
Good Read:
What is the difference between a definition and a declaration?
I believe you would want to get information on dynamically allocated objects because automatic objects only live long enough in their scope, they will automagically destroyed so they don’t usually cause any problems.
For dynamic objects You can use memory profiling tools like valgrind with Massif or you could replace
newanddeleteoperators for your class and collect the diagnostic information.EDIT: To address the updated Q.
vis created when the scope in which it is declared starts and the statement where it is declared gets executed.vis destroyed once the scope ends i.e}is reached.This concept is used for forming the basis of one of the most widely used concepts in C++ known as Resource Allocation is Initialization(RAII). Every C++ programmer absolutely must know about it.
It is simple to demonstrate and verify the creation and destruction of the objects through this small modified code sample:
The output is: