Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get the range of memory addresses that are available on the heap?

It seems to me that this is how memory works in C++:

If you use new then you are asking the compiler's implementation to give you some memory (any memory) from the heap.

If you use the placement new syntax, the you are asking to re-allocate a specific memory location that you already know the address of (let's just assume it is also from the heap) which presumably was also originally allocated from the new operator at some point.

My question is this:

Is there anyway to know which memory locations are available to your program a priori (i.e. without re-allocating memory from the heap that was already given to you by the new operator)?

Is the memory in the heap contiguous? If so, can you find out where it starts and where it ends?

p.s. Just trying to get as close to the metal as possible as fast as possible...

like image 527
Jimmy Avatar asked Jan 20 '23 00:01

Jimmy


2 Answers

Not in any portable way. Modern operating systems tend to use paging (aka virtual memory) anyway, so that the amount of memory available is not a question that can be easily answered.

There is no requirement for the memory in the heap to be contiguous, if you need that you are going to have to write your own heap, which isn't so hard to do.

like image 106
john Avatar answered Jan 21 '23 15:01

john


The memory available to your program "a priori" contains the variables you have defined. The compiler has calculated exactly how much the program needs. There is nothing "extra" you can use for something else.

New objects you need to create dynamically are allocated from the free store (aka heap), possibly by using new but more often by using containers from the library like std::vector.

The language standard says nothing about how this works in any detail, just how it can be used.

like image 31
Bo Persson Avatar answered Jan 21 '23 13:01

Bo Persson