Page 1 of 1

[SOLVED]noob questions about dynamic memory allocation

Posted: Fri Dec 17, 2010 9:57 pm
by optLog
If you allocate a block of memory, such as an array of five integers. How does the system know how much memory to free up when you call delete[]?
And if you did something like this

Code: Select all

int *intArray = new int[0];
delete[] intArray;
would "new int[0]" actually reserve anything (like even a memory address?) and would "delete[]" mess up any memory?

Re: noob questions about dynamic memory allocation

Posted: Sat Dec 18, 2010 2:19 am
by Milch
I think this is stored somewhere internally.
I once asked my teacher about it (he was a compiler programmer) and he said that they dont want to make you have access to this number because it would restrict the compiler-programmers
(+it would propably fuck up the internal memory management if you change this number)

Re: noob questions about dynamic memory allocation

Posted: Sat Dec 18, 2010 5:54 pm
by short
Milch wrote:I think this is stored somewhere internally.
I once asked my teacher about it (he was a compiler programmer) and he said that they dont want to make you have access to this number because it would restrict the compiler-programmers
(+it would probably fuck up the internal memory management if you change this number)
Yeah.

The "plain" operator delete is used to delete individual objects; delete[] is used to delete arrays. To deallocate space allocated by new, delete and delete [] must be able to determine the size of the object allocated. This implies that an object allocated using the standard implementation of new will occupy slightly more space than a static object. Typically, one world is used to hold the object's size. -- Bjarne's C++ Programming Language 3rd ed (p 128)

So yeah, the size is stored internally within the object. You could probably find it if you examine the memory your object is stored in.

Re: [SOLVED]noob questions about dynamic memory allocation

Posted: Sun Dec 19, 2010 11:25 am
by optLog
I made a memory leaking application to see what would happen if I dynamically allocated an array with zero elements in it. I had it so that it would create the zero length array a thousand times. Every time I did this the application leaked about sixteen KB of memory. I then modified the program to delete the array after it was allocated and the program stopped leaking memory. I only have a windows machine so I don't know if this happens with other OS's.