views:

56

answers:

4

When we dynamically allocate memory, does the memory occupies the continuous memory segment.

A: 

Not necessarily, and usually no. There may be different allocation mechanisms.

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

Pavel Radzivilovsky
+3  A: 

Yes, the allocation is virtually contiguous (if you got it with one malloc() call). It may not be physically contiguous, but from an application perspective, you don't usually care.

WhirlWind
+1  A: 

It depends on 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 each have 100 bytes allocated to them. However, you cannot assume that the 100 bytes allocated to b will be right after the 100 bytes allocated to a, or vice versa, or anything, in fact, about their positions relative to each other. So in that sense, no, they are not contiguous.

Within each block of 100 bytes, however, those 100 bytes are contiguous from the viewpoint of your program. That is, a[1] is one byte away from a[0] and a[2].

RarrRarrRarr
+1  A: 

You should separate the concept of virtual memory from the one of physical memory.

While every allocated chunk (either a single object, or an array of objects) has a contiguous virtual space (starting from the address that your dynamic memory allocator gives to you), it can be splitted in real memory according to how the underlying operating system manages memory.

Of course if virtual memory is not present they will correspond, otherwise it's contiguous for the program that is using it but not in the physical layout of the memory..

Jack