Dynamic memory allocation

When we dynamically allocate memory, does the memory occupy a segment of contiguous memory.

+2


source to share


4 answers


Yes, allocation is nearly continuous (if you got it with one call to malloc ()). It may not be physically contiguous, but from the point of view of the application, as a rule, you are not interested.



+4


source


It depends what exactly you are asking. For example, let's say you have this C code:

char* a = malloc(100);
char* b = malloc(100);

      



a and b pointers have 100 bytes allocated to them. However, you cannot assume that 100 bytes allocated to b will be considered correct after 100 bytes allocated to a, or vice versa, or anything else, in fact, about their positions relative to each other. Therefore, in this sense, no, they are not adjacent.

However, in every block of 100 bytes, those 100 bytes are contiguous from the point of view of your program. That is, it a[1]

is one byte away from a[0]

and a[2]

.

+2


source


You have to decouple the concept of virtual memory from physical memory.

While each allocated chunk (either a single object or an array of objects) has contiguous virtual space (starting at the address the heap allocator gives you), it can be partitioned in real memory according to how the main operating system manages memory.

Of course, if there is no virtual memory, they will match, otherwise it will be contiguous to the program being used, but not in the physical memory layout.

+2


source


Not necessary, and usually not. There can be different distribution mechanisms.

Many will store metadata between allocated chunks, split heaps according to object sizes and other things. You cannot rely on the continuity of the returned pointers.

0


source







All Articles