2

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

Sky Sanders
37.2k9 gold badges72 silver badges91 bronze badges
asked Apr 10, 2010 at 17:58

4 Answers 4

4

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.

answered Apr 10, 2010 at 18:00
Sign up to request clarification or add additional context in comments.

Comments

2

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

answered Apr 10, 2010 at 18:04

Comments

2

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

answered Apr 10, 2010 at 18:04

Comments

0

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.

answered Apr 10, 2010 at 17:59

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.