Ankur
Ankur

Reputation: 1199

dynamic memory allocation

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

Upvotes: 2

Views: 268

Answers (4)

Jack
Jack

Reputation: 133587

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..

Upvotes: 2

RarrRarrRarr
RarrRarrRarr

Reputation: 3900

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].

Upvotes: 2

WhirlWind
WhirlWind

Reputation: 14112

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.

Upvotes: 4

Pavel Radzivilovsky
Pavel Radzivilovsky

Reputation: 19114

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.

Upvotes: 0

Related Questions