Sign in to follow this  
Captain Duh

Delete this or delete these

Recommended Posts

Captain Duh    134
Here is a tricky "delete" question. Imagine you have a private member that will point to another user-defined type. Later in the execution the member will allocate memory for its needs. Throughout the life of the program, the member will need to clean out (delete) and set up new memory for use. Here is the issue I am having: when I go into the method that sets up the member’s data, I tell the program to check if old data is present and if it is, then delete it. My program crashes when it checks and attempts deletion and brings me to a runtime error involving invalid memory to delete. I think what this means is that the program is trying to delete an array when only a single memory location is actually involved. I think it might be a case of using the "delete []" when a simple "delete" is required. So my question is that if the member is simply defined and not yet allocating, how can you check if an array was allocated or if the pointer is simply waiting for allocation? Here is an example of what I mean: class paint{ public: paint(); //constructor void setup(); //where the member will check and delete then reallocate private: color *newcolor; // will later allocate an array of new colors } paint::paint(){ //newcolor not yet initialized } void paint::setup(){ if(newcolor) //check if old array is present and delete if it is delete [] newcolor; //now make room for new color data } Is the call to "delete []" newcolor valid? I know it would be in later calls when the member allocates an array of information. But on the first call when no data has yet been allocated, is this still legal? What is the best method to check?

Share this post

Link to post
Share on other sites
jflanglois    1020
A few things need to be addressed here.

1. Pointers are not default constructed (at least not as member/automatic variables), nor does operator delete set pointers to null (0). Make sure you are initializing your pointer correctly.

2. you must use delete[] when you use new[] and you must use delete when you use new.

So, to answer your question, your setup method is valid only if you are certain that you allocated with new[]. Also, it is invalid anyway if you did not initialize your pointer to null upon default construction of the paint class.

To save yourself the trouble, use an STL sequence such as std::vector.


Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this