delete a char *

I have a class "Meeting" with two data members, one is of type "Date" which I defined myself,the other represents a description and is defined as a char *.

In my destructor I wish to free the memory used by the members.
This works fine for the Date object, but when I try to delete the char * the program crashes.

I know char * is a special case and that it can be interpreted as being an array. So how would I do this?

The char * member gets its value from a parameter passed with the constructor.
Depending on how you declared it, it may not need to (and shouldn't) be freed. Seeing as how your program is crashing, that's probably the case.
You can't just call delete on any object you find unsavory. You must have first dynamically allocated it with the new operator. At that point it is allocated from the heap and can be deleted (and should be deleted) by use of the delete operator. You cannot delete objects allocated normally, on the stack.
And to delete an array, you add subscripts onto it. It's somewhere in the references.
I see that I need to use new in order to be able to use delete. Should I use memcpy to get the data from the constructor into the member created with 'new'.

Here's my class:
1
2
3
4
5
6
7
8
9
10
11
class Afspraak
{
public:
	Afspraak(Datum *datum, char *beschrijving) :
	  p_datum(datum), p_beschrijving(beschrijving) {}
    
    ~Afspraak();
private:
	Datum * p_datum;
	char * p_beschrijving;
};
As far as I recall, no. You just create the object as a pointer and initialize it with new (but my memory is bad). Then you can refer to that allocated memory.
Here's my question - for what do you need the dynamic allocation? If you don't actually have a use for it (such as declaring arrays out of variable sizes but you could just use a standard container) then it's easier and clearer to just create from the stack.
Well, I think the point of the exercise (yes, it's an exercise) is to stumble upon this pitfall since it's an exercise about destructors and dynamic allocation.

anyways, I've updated the code with memcpy() and it seems to work just fine.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

class Afspraak
{
public:
	Afspraak(Datum *datum, char *beschrijving) :
	  p_datum(datum) 
	  {
		  p_beschrijving = new char[80];
		  memcpy(p_beschrijving, beschrijving, 80);
	  }
    
    ~Afspraak();
private:
	Datum * p_datum;
	char * p_beschrijving;
};
Use strcpy() or strncpy() to copy strings. You don't know if beschrijving is actually shorter than 80 characters.
If I use strcpy() and strlen(beschrijving) > 80 then it won't fit in p_beschrijving anyways because I have declared p_beschrijving with new char[80].

Or am I missing something ?
That's the beauty of dynamic allocation. Just allocate an array of strlen()+1 characters.
Last edited on
hm nice, didn't see that before.

Thanks for the tip.
Topic archived. No new replies allowed.