I'm learning C++ at the moment and there's something I'm unclear on.
If I create a function that allocates memory for an array of some type and then returns the newly-created pointer, given that the pointer is just a memory address, will a corresponding delete
statement clean up all of the allocated memory correctly, or will only the first element be deallocated, creating a memory leak with the remainder of the array? If it is cleaned up correctly, how does C++ know what to deallocate, given my presumed loss of context inherent in the return type?
int* AllocateSomething()
{
int *arr = new int[100];
// fill the array with something...
return arr;
}
int main()
{
int* p = AllocateSomething();
delete p; // what will this do?
delete[] p; // how would this know how much memory to delete?
}
Normally I would just write some test code to figure out the answer to something but given that accessing unallocated memory results in undefined behaviour, I'm not exactly sure what I would test for.