Archived

This topic is now archived and is closed to further replies.

C++ delete question

This topic is 5313 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

If I declare an array as such: int* array = new int[10]; there is no way to tell how long the variable ''array'' is without using another variable. So how does calling delete[] array; work, if ''array'' can be of any size? How does delete know how much memory to free?

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Because it finds it.. !=NULL i''d guess.

Share this post


Link to post
Share on other sites
it allocated much more extra bytes. Sometime ago I figuered out that it was 18 bytes if I''m not mistaking before the pointer. But you shouldn''t use that, because you never know if it will work on other systems/windows versions, and you can be quite sure it won''t be cross platform.

My Site

Share this post


Link to post
Share on other sites
Because you told the compiler how much to allocate when you said new int[10], so the compiler stores the number with the memory it allocated, and when you call delete [] on that variable, it knows how much to delete.

Share this post


Link to post
Share on other sites
Looks this is what is happening!!

When you declare int *ARRAY = new int[10];, the compiler goes to the heap (a section in where you can allocate memory that lies on RAM) and set memory aside for your data. In this case you are telling to the compiler to set aside 10 int''s or 10 * 4 = 40 bytes. But how do the compiler knows where the memory is?..Well that is why we declare variables...I this case ARRAY is a constant Address,,,or a Pointer to the first byte of the 40 bytes we set aside on memory. Therefore, when you call
delete[] ARRAY;
Your compiler goes to the Address that ARRAY is holding and free the same amount of bytes that you set aside when you reserved that portion of data.
In this case 40 bytes.

ASW

Share this post


Link to post
Share on other sites
Guest Anonymous Poster
Now explain the magic behind stack unwinding

Share this post


Link to post
Share on other sites
quote:
Original post by C-Junkie
i decree that from now on, this question will be answered with two words, "its magic."
...but that doesn''t make any sense. You want: "It''s magic.", with the apostrophe.

Share this post


Link to post
Share on other sites