Pritesh Jain
Pritesh Jain

Reputation: 9146

Is this the proper way of freeing Pointer Memory in c++

this is a example, I am struck with whether it is a a proper way of freeing the pointer assigned memory

char* functionTest()  
{  
    char *a = new char[10];  
    return a;  
}  
int main()  
{  
    char *b;  
    b=functionTest();  
    delete[] b;  
    return 0;  
}

This is a very beginner question but still would like to clear my doubt. edited from delete to delete[] thanks @sharptooth. thanks in advance.

Upvotes: 4

Views: 186

Answers (2)

CashCow
CashCow

Reputation: 31435

Technically correct C++ (as of this time with the edit using delete[])

The code would compile and run without errors.

However in production C++ code you will very rarely use new[] and delete[], and will be far more likely to use vector, or for string handling use string.

If you do really want to allocate an array with new[] you may well wish to use boost::shared_array to manage its deletion. Failing that you could use shared_ptr but would have to put in your own deleter that calls delete[].

This technique is called RAII (Resource Acquisition Is Initialisation), which ensures that for any resource you allocate, you are already taking care of its subsequent disposal regardless of what happens subsequently (including any exceptions that may be thrown).

Upvotes: 4

Frederik Slijkerman
Frederik Slijkerman

Reputation: 6529

Here's a nice technical description of the differences between delete and delete[]: http://blogs.msdn.com/b/oldnewthing/archive/2004/02/03/66660.aspx

Upvotes: 0

Related Questions