0

I'm a little bit confused on how to correctly allocate/deallocate dynamical array of objects. Here is my scenario:

class Tuple { public: Tuple(int columns); ~Tuple(); void set(int i, string d); string get(int i); int columnCount(); private: string *data; int columns; }; Tuple::Tuple(int columns) { this->columns = columns > 0 ? columns : 0; if (this->columns > 0) { data = new string[this->columns]; } else { data = 0; } } Tuple::~Tuple() { if (columns > 0) { delete data; } } 

Now, when I call the following code I get a segfault:

Tuple *t = new Tuple(4); //some code delete t; 

What is wrong with my denstructor?

3 Answers 3

4

You need to use array delete operator in your destructor:

delete [] data; 

The destructor can be written as

Tuple::~Tuple() { delete [] data; } 
Sign up to request clarification or add additional context in comments.

2 Comments

@Dan do not judge and you won't be judged
@LightnessRacesinOrbit - there are reproducible facts and there are false confidence and baseless speculations
2

What is wrong with my denstructor?

You wrote delete instead of delete[].

BTW you're also missing a copy constructor and assignment operator, so your class is more subtly broken and rather susceptible to memory leaks.

how to correctly allocate/deallocate dynamical array of objects.

Don't.

Use a std::vector<std::string>.

3 Comments

@the_candyman: Why use a vector? So that its allocation and de-allocation is managed for you and you don't need to worry about any of this (including the three bugs in your attempt). In case you were wondering, there is no downside.
ok, but what if I want to allocate exactly a certain amount of memory?
@the_candyman: Then ask the vector to do that. Read the chapter about vectors in your C++ book. They're really easy to use: way easier than this manual memory management gubbins.
2

I encourage you to look up the difference between:

delete
delete (nothrow_t)
delete []
delete [] (nothrow_t)

and look into their new equivalents, and when one should be used over the other.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.