I have a doubt about the stack memory.
I have the next C++ source file named program.c:
class BigVector
{
  int foo[500000];
  public:
  void addInformation(int value)
  {
    for (int i(0); i < 500000; ++i)
    {
        foo[i] = value;
    }
  }
};
int compute(int a, int b)
{
    int result = a + b;
    int result1 = 10;
    int result2 = 11;
    int result3 = 12;
    int result4 = 13;
    int result5 = 14;
    int result6 = 15;
    int result7 = 16;
    int result8 = 17;
    int result9 = 18;
    int result10 = 19;
    int result11 = 20;
    int result12 = 21;
    int result13 = 22;
    int result14 = 23;
    int result15 = 24;
    int result16 = 25;
    int result17 = 26;
    int result18 = 27;
    int result19 = 28;
    int result20 = 29;
    {
      int foo[500000];
      for (int i(0); i < 500000; ++i)
      {
        foo[i] = result20;
      }
    }
    BigVector* bigVector = new BigVector;
    bigVector->addInformation(result20);
    delete bigVector;
    return result;
}
int main()
{
    int a = 10;
    int a1 = 43;
    int a2 = 21;
    a = compute(a1, a2);
    return 0;
}
I have compiled the program with the next command on a Ubuntu machine:
g++ -m32 -O0 -g -o program program.c
Then, I debugged the program using the gdb. I set breakpoints on the next lines:
- Before 'compute' call on the main function.
- On result20 = 29.
- Before addInformation.
- Before delete bigVector.
- On the return result.
- On the return 0.
Then, I was debugging while I was seeing the memory usage with 'top' program. And these are the results.
- 1348 KB.
- 1348 KB.
- 3628 KB. The 500000 integer elements were filled.
- 5740 KB. The addInformation was performed.
- 3800 KB. The delete was performed.
- 3800 KB.
I supose that the stack memory is released when all the local variables related to 'compute' function are out of scope, but I do not understand why reason the memory in the point 6) is not equal to the memory in the point 1). I do not know neither why reason in the point 4) the value is not equal to 1348 KB, there is a nested block and I suposse that the foo variable should be freed.
Can someone help me understand this?
Best regards.
I'm trying to understand the stack memory. I expect that the stack memory be freed and this be shown in top command.
