Click here to Skip to main content
15,173,746 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
int *ptr;
ptr=new int a[20];

delete memory created to 20 integers without using delete
Posted
Comments
Richard MacCutchan 1-Oct-14 9:37am
   
You can't. As I suggested in your other question, go and read your course notes.
Rob Grainger 1-Oct-14 11:58am
   
Of course you could use a smart pointer...

std::auto_ptr<int> a(new int[20]);

Which will automatically delete the memory when the variable 'a' goes out of scope. But really that's still calling delete[] under the covers.

Note - you need to use delete[] rather than delete to free an array.

You could use a number of ways to to do it without literally writing the delete operator in your program:

C++
#include <memory>
int main()
{
    int *ptr=new int[20];
    std::allocator<int>().deallocate(ptr, 20);
}


C++
#include <memory>
int main()
{
    int *ptr=new int[20];
    std::default_delete<int[]>()(ptr);
}


XML
#include <memory>
int main()
{
    int *ptr=new int[20];
    std::unique_ptr<int[]> p(ptr);
}


XML
#include <boost/smart_ptr.hpp>
int main()
{
    int *ptr=new int[20];
    boost::scoped_array<int> p(ptr);
}


etc.

All of these somewhere internally execute delete[] with a copy of your ptr as the argument which is what actually deallocates that memory.
   
v2
Comments
Usman Hunjra 3-Oct-14 17:06pm
   
Gr8 .. :)
the language C++ has some rules, for instance that memory which is allocated the new has to be freed with release.

You can:

1. overwrite the command new and delete with your own implementation
2. use other methods for memory managment like malloc and free.
3. allocate memory in scopes.
4. use some auto_ptr. (advanced technology)


But never ever ferget: be a good citizen and if you want to develop software you should stick to the rules.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900