Is/How is the heap organized?

Hey everyone!

So I'm wondering something about the heap. My book (a crappy one) defines it as "a huge, amorphous block of memory". If you allocate an array on the heap with:

int * blah = new int[10];

The addresses of those ten integers is consecutive, right? I'm just making this assumption because you can access them by doing *blah, *(blah+1), *(blah+2), etc. Is that assumption correct?

If it isn't, does the heap just find space for an array if there is enough total space?

If it is, what happens if you have enough space in a heap for an array, but not enough consecutive space? Let's say you have 10MB free out of a total of 20MB, but it goes 5 free, 10 used, 5 free. Then you try to allocate an array of size 8MB. What happens?

Thanks!
How deep do you want to go? Do you want to take the blue pill or red pill? Do you want to know about your program's view of its memory space or the kernel's view of the program's memory space?
Assuming you are asking from a userland standpoint...

Your assumption is correct. In your example, new will throw std::bad_alloc.
However, note that a modern OS could return a valid pointer even in that case. The OS may choose to not physically allocate any memory until data is written. By then, it has a few choices. If there's enough contiguous memory, it can do a regular allocation; if there isn't, it can make room by moving unused pages to swap space; if there's just not enough memory at all, actually, I don't know what happens, but it would probably crash the program, or maybe suspend it until there's more memory.
I answered the question based upon the assumption that OP's phrase "not enough consecutive space"
applied to the process' virtual address space and not physical memory, since the MMU can make
non-contiguous physical memory look contiguous to the app.
Okay, I wasn't correcting you, I just thought OP was talking about physical memory.
So, something translates physical memory into virtual memory, so even though in physical memory there may not be enough contiguous space, there could be in the virtual memory, the memory the program "sees" ?
Topic archived. No new replies allowed.