Question:
C++: delete [] charArray crashing program?
A
2009-02-03 10:18:47 UTC
I have a class.
That class has a character array in it.
In the deconstructor for that class, I delete[] that character array.

This delete line seems to give me an memory allocation error. I'm using conditional statements to ensure the array is not NULL when I use it. What else could cause it to crash?
Three answers:
mez13526
2009-02-03 10:36:55 UTC
You most certainly want to call delete in your destructor on anything you called new on previously (in that class).

However, delete is also the time when most debugging runtime systems do memory corruption tests.

Make sure when you use that memory, you don't overwrite past the end of the array (or before the beginning).
Jon B
2009-02-03 10:25:42 UTC
You typically don't want to call delete in a class's destructor method, especially not for a class member. I wouldn't bother defining a destructor method, since the de-allocation when you delete the containing object should get rid of its member character array.



edit: As the answer below says, if the character array is instantiated with a new call within the class's constructor, then you would want to call delete in the destructor. I'm assuming, however, that the character array was not created by a call to new.



Basically, if the member is a pointer, call delete. If the member is contained in the object, don't.
beaman
2017-01-03 01:13:38 UTC
#contain 79abd8cf35895c56ccd64592e395fedad7bbbedeca3fe2e0d955c5355dbe utilizing namespace std; char * tolowercase(char * ptr) { char *temp = ptr; jointly as( *ptr ) { *ptr = tolower(*ptr); // Renders lowercase ptr++; } return temp; // this is so the return fee is the initiating of the string no longer the top. } int important() { char str[d64592e395fedad7bbbedeca3fe2e0d64592e395fedad7bbbedeca3fe2e0] = "hi international!"; // substitute this line so as that "hi international!" is saved in the string array. till now you had a pointer to reminiscence containing "hi international!". strcpy (str, tolowercase(str)); cout << str; return forty; } this could paintings devoid of 'crashing'.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...