By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,061 Members | 1,563 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,061 IT Pros & Developers. It's quick & easy.

{malloc, new} and {free, delete}

P: 1
when i create an array through malloc, i use free to free it. If i create the same array using new operator (e.g.) int a[] = new int(20); then i have to user 'delete[] a'. But i don't use '[]' in free system call. Please clear my doubt and if some one suggest me a book that explain details like this stuf? I don't want some internals details like hoem memory manager is workibng. A bok that just explain me the concept of how this is done?
Aug 6 '07 #1
Share this Question
Share on Google+
1 Reply


Expert 10K+
P: 11,448
when i create an array through malloc, i use free to free it. If i create the same array using new operator (e.g.) int a[] = new int(20); then i have to user 'delete[] a'. But i don't use '[]' in free system call. Please clear my doubt and if some one suggest me a book that explain details like this stuf? I don't want some internals details like hoem memory manager is workibng. A bok that just explain me the concept of how this is done?
The free() function doesn't care what you free; any non-null pointer will be free'd
if it has been malloc'd before; even more, free() doesn't care what the content
of the memory pointed to by that pointer contains. If it contains a last reference
(pointer) to some other memory: so be it; you've got yourself a memory leak then.

Delete does a lot more but it has to know whether or not the pointer you supply
it is a pointer to just one object or possibly more object. You tell that to the
delete operator by supplying those square brackets. They need to pair up with
your new operator, i.e. if you new'd an array, you should delete [] an array.

kind regards,

Jos
Aug 6 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.