c++memorylldbresource-management

top may be showing incorrect memory usage


I am writing a simple C++ program on Mac OS. I have just

int main()
{
    int *n = new int[50000000];
}

I launch this program in lldb, and put a breakpoint at the line where n is allocated. Then I launch top in another tab, I see that memory usage is 336K pre-allocation. When I do n inside lldb, so that the allocation for n happens, I expect to my memory usage to go up. However, top shows me the same amount of memory used by my program. What could be the reason for this? I am trying to understand how memory allocation happens in C++, which is why I am doing this.

I have not exited the scope of main. When I check top again, I am sitting at closing curly brace for main.


Solution

  • The top command shows the process stats as viewed by the operating system. It shows how much memory was allocated to the process, but not how much of this memory is effectively in use. It's not accurate for monitoring memory allocation.

    Memory allocation with heap and free store is implementation dependent in C++. But tt's usually not mapped one to one with OS allocation calls. For performance reasons (calls to the OS are slower than calls inside your userland code), the memory is received from OS in larger chunks:

    From your observations, I guess that this initial allocation is larger than 50 MB. Try with a much larger value to see the difference.

    If you want to track memory consumption more precisely, you need some profiling tools, for example valgrind or heap command