-
deleting objects
Hello,
I've declared the following class:
Code:
class person
{
public:
int age;
char *name;
person(char *p_name, int p_age);
~person() {
delete[] name;
}
};
In my main program I've declared an array of persons. At the end of my program I'm deleting those objects as following:
Code:
for(i = 0; i < 10; i++) delete persons[i];
Somehow I'm getting the following error:
DAMAGE: after Normal block (#43) at 0x00431AF0.
I'm getting the same error when I'm deleting the name of a person by (without the [])
Can someone tell me what the error means, how I can avoid it and how I can delete the names in the object destructor? (Maybe it isn't necessary at all, but it seems to me, since I'm using a pointer.)
-
are you sure name isn't a wild pointer? for each delete you should have a new.
-
In the class constructor, set name to NULL. Then, in the destructor, check to see if name == NULL. If its not, delete it. you may also get the DAMAGE: warning if you attempt to write out of bounds of your allocation:
Code:
char* n = NULL;
n = new char[10];
n[10] = NULL;
...
delete [] name;
On the delete, you will get that warning. Check any string modifications that you do to make sure that you dont write out of bounds.
Z.
-
The constructor is defined like this:
Code:
person::person(char *p_name, int p_age): age(p_age)
{
int len;
len = strlen(p_name);
name = new char[len];
strcpy(name, p_name);
}
I think it's allright.
Do I actually have to delete strings in the destructor of a class, or are they cleared automatically?
-
a) are the persons allocated dynamically (with new)
b) why don't you use the string class?
-
c) why don't you use vector or list ;)