int *a, *b;
a = new int[10];
b = new int(12);
b = a; // I know there's memory leak, but let's ignore it first
delete [] b; // line L
Will the entire array be deleted successfully?
Yes, memory will successfully be freed since the pointer a
was set to point to an array of 10 integers
a = new int[10];
then the same memory location address is stored into b
b = a;
therefore the delete[]
line correctly deallocates the array chunk
delete [] b;
As you stated the code also leaks the integer variable 12 that was originally allocated and pointed to by b
.
As a sidenote calling delete[]
to free memory not associated with an array (specifically with a static type mismatch - see [expr.delete]/p3) would have triggered undefined behavior.
Now for some internals on where is the size information stored when allocating memory.
Compilers have some degree of freedom (cfr. §5.3.4/10) when it comes to memory allocation requests (e.g. they can "group" memory allocation requests).
When you call new
without a supplied allocator, whether it will call malloc
or not, it is implementation defined
[new.delete.single]
Executes a loop: Within the loop, the function first attempts to allocate the requested storage.
Whether the attempt involves a call to the Standard C library function malloc is unspecified.
Assuming it calls malloc()
(on recent Windows systems it calls the UCRT), attempting to allocate space means doing book-keeping with paged virtual memory, and that's what malloc usually does.
Your size information gets passed along together with other data on how to allocate the memory you requested.
C libraries like glibc take care of alignment, memory guards and allocation of a new page (if necessary) so this might end up in the kernel via a system call.
There is no "standard" way to get that info back from the address only since it's an implementation detail. As many have suggested, if you were to need such an info you could
- store the size somewhere
- use
sizeof()
with an array type
- even better for C++: use a
std::vector<>
That info is furthermore associated with a memory allocation, both of your secondary cases (i.e. substituting the L
line with
b = a + 1; delete [] b;
or
a++; delete [] a;
will end in tears since those addresses aren't associated with a valid allocation.