Click here to Skip to main content
15,911,786 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have my following ansi C code example:

C++
void Example1()
{
 int i;
 int *arr = (int*)malloc(5*sizeof(int)); // int arr[5];

 for (i=0;i<5;i++)
   arr[i]=i;
 //do something
 //...
}

void Example2()
{
 int j;
 j=0;
 //do some thing
 //...
}

void main()
{
 Example1(); 
 Example2();
}


when the program run, the "Example1" function is called first and then followed the "Example2" function.

Assumaply, when the compiled program in the "Example1", "i" variable is allocated to the 0x00000000 memory address and "arr" is allocated to the 0x00000004 memory address.
After passing through to the end of line in "Example1" and go to the "Example2" and starting process to allocated to the "j" variable. Now, stop it. I have some following questions and really need you guys to help me out.

Where exactly address location of "j" variable is?
Is the "Example1" after completing its mission in main program automatically free the memory of "i" and "arr" variable?
Every specific compiler have a mechanism automatically free the memory after using or not? (or depend on something?)

Thanks guys in advance
Posted
Comments
Albert Holguin 4-Oct-11 22:59pm    
is this homework?
tamcntt1985 4-Oct-11 23:23pm    
Not a homework, my friend.
Just for more knowledge and experience in workplace.

1 solution

Rule 1, anything you malloc() has to be free()'ed by you, there is no magic that will do that for you.

Rule 2, local variables (in your case, i, j, and arr) are stored locally, usually on the stack. They disappear when your routine exits.

Rule 3, stacks tend to get dirty with calls / local variables of other things you are doing so you cannot rely on their contents if you did not initialize it yourself. The fact that 'i' and 'j' may have occupied the same location on the stack cannot be relied on provide any meaningful information about the "leftover variables".

Rule 4, compilers are free to 'optimize away' local variables. So, the compiler may decide that 'j' can really be a processor register and end up occupying no memory or stack at all.

Rule 5, when you get away from simple language types like 'char' or 'int' and start using C++ classes, local variables that are instantiations of classes have their destructor called when the function exits (technically, when the variable goes out of scope). That's about the only magic and help the compiler gives you.
 
Share this answer
 
Comments
Richard MacCutchan 5-Oct-11 4:25am    
+5, excellent description.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900