C++ new / new[], how is it allocating memory?

后端 未结 3 707
遥遥无期
遥遥无期 2021-01-26 17:09

I would like to now how those instructions are allocating memory.

For example what if I got code:

x = new int[5]; 
y = new int[5];

If t

相关标签:
3条回答
  • 2021-01-26 17:51

    Each process has different segments associated which are divided among the process address space : 1) The text segment :: Where your code is placed 2) Stack Segment :: Process stack 3) Data Segment :: This is where memory by "new" is reserved. Besides that it also store initialized and uninitialized static data (bss etc).

    So , whenever you call a new function (which i guess uses malloc internally , but the new class makes it much safer to handle memory) it allocates the specified number of bytes in the data segment. Ofcourse the address you print while running the program is virtual and needs to be translated to physical address..but that is not our headache and the OS Memory management unit does that for us.

    0 讨论(0)
  • 2021-01-26 17:52

    You didn't find it in the manual because it's not specified by the standard. That is, most of the time x and y will be side by side (go ahead and cout<< hex << their addresses).

    But nothing in the standard forces this so you can't rely on it.

    0 讨论(0)
  • 2021-01-26 18:00

    A typical allocator implementation will first call the operating system to get huge block of memory, and then to satisfy your request it will give you a piece of that memory, this is known as suballocation. If it runs out of memory, it will get more from the operating system.

    The allocator must keep track of both all the big blocks it got from the operating system and also all the small blocks it handed out to its clients. It also must accept blocks back from clients.

    A typical suballocation algorithm keeps a list of returned blocks of each size called a freelist and always tries to satisfy a request from the freelist, only going to the main block if the freelist is empty. This particular implementation technique is extremely fast and quite efficient for average programs, though it has woeful fragmentation properties if request sizes are all over the place (which is not usual for most programs).

    Modern allocators like GNU's malloc implementation are complex, but have been built with many decades of experience and should be considered so good that it is very rare to need to write your own specialised suballocator.

    0 讨论(0)
提交回复
热议问题