Is dynamically allocated memory contiguous in C++? In C? Details would
be appreciated.
C questions are off-topic here unless they are somehow also relevant
to C++ (comp.lang.c is the place to ask), so I'll limit myself to the
question concerning "new".
Do you mean, contiguous across different calls to new? If so, the
answer is: not necessarily, because it is implementation-defined how
new obtains and utilizes its raw memory. I would say, no, because
unused blocks of memory released by calling delete are normally
recycled within the total memory used by the process taken from its
free store (i.e. heap memory) provided by the operating system. Often,
the memory is only returned to the operating system when the process
ends, but that is also an implementation-specific detail which can be
quite different on another compiler and operating system.
A class can also overload new and delete to use a different memory
allocation scheme.
Otherwise, I don't really understand your question. Allocations
performed by new allocate a single object of a given type. Allocations
performed by new[] allocate arrays of objects of the same type.
Although the memory occupied by the array is guaranteed to be
contiguous, and the memory occupied by any given object is contiguous,
it is implementation-defined how the compiler lays out the individual
members of the object in that memory. The implementation (i.e. your
compiler) is free to add padding bytes between the individual members
for purposes of alignment and can be influenced by different
optimization and alignment settings at compile-time (e.g., see the
documentation for "#pragma pack" if your compiler supports it).
Consider the following:
struct X {
short a;
char b;
int c;
};
What is sizeof X here? Depending on the compiler settings, you will
most likely get an additional byte of padding thrown in after the char
member. However, it is also possible that there are two extra bytes
after the short member as well. Switch around the order of the members
and see if you get different results.
Of course, an instance of a class can allocate additional memory and
store just the pointer to that memory. When querying the size of such
an object with sizeof(), only the memory occupied by the pointer would
count towards the total size of the object.
If you want more details, I suggest you get a copy of the C++ standard
at:
http://www.ansi.org