0

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:

  1. Before 'compute' call on the main function.
  2. On result20 = 29.
  3. Before addInformation.
  4. Before delete bigVector.
  5. On the return result.
  6. On the return 0.

Then, I was debugging while I was seeing the memory usage with 'top' program. And these are the results.

  1. 1348 KB.
  2. 1348 KB.
  3. 3628 KB. The 500000 integer elements were filled.
  4. 5740 KB. The addInformation was performed.
  5. 3800 KB. The delete was performed.
  6. 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.

  • 1
    `BigVector* bigVector = new BigVector;` -- This is allocated from the free-store (heap), not the stack. – PaulMcKenzie May 14 '23 at 01:27
  • Yes, I know this but I have used this line to check the changes in the memory using 'top'. – user21893814 May 14 '23 at 06:55
  • "I have the next C++ source file named program.c" - Don't name C++ source files with a `.c` extension, that's for C source files. Use `.cc`, `.cpp` or one of the other extensions the compiler will interpret as C++. See also: https://gcc.gnu.org/onlinedocs/gcc-13.1.0/gcc/Overall-Options.html – Jesper Juhl May 14 '23 at 10:04

0 Answers0