1

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.

user2048925
  • 63
  • 1
  • 5
  • 3
    The allocation is probably only reserving virtual address space. The actual memory will not be allocated by the OS until you touch each page. Add a for loop that writes a single byte every 4K. – Richard Critten Jul 23 '16 at 23:57

1 Answers1

1

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:

  • when the c++ runtime starts, it usually allocates some memory from the OS, in order to allocate memory it needs for standard library objects, and to initalize the free store to quickly satisfy allocation request.
  • Only if this initial memory is exhausted will the standard library allocate more memory from the operating system.
  • And allocation is done again in larger chunks, so that not every new would raise an OS call.

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

Christophe
  • 68,716
  • 7
  • 72
  • 138