Hunter
Hunter

Reputation: 357

Deleting memory in c++

I'm trying to rewrite my code using dynamic memory allocation, and I'm using, amongst others, this question (and answers) to help me. So following Johanes Shaub's advice, I've declared my 2d array as:

double (*q_1_matrix)[TIME] = new double[SPACE][TIME];

When I run my code now everything seems to work fine. But when I add the following line to deallocate the memory again:

for(i = 0; i < SPACE; ++i) {
    delete [] q_1_matrix[i];
}
delete [] q_1_matrix;

then I get the warning: deleting array ‘*(q_1_matrix + ((sizetype)(((long unsigned int)i) * 800ul)))’ [enabled by default] delete [] q_1_matrix[i]; and subsequently I get a Segmentation fault (core dumped).

Anybody knows what I'm doing wrong?

Upvotes: 0

Views: 72

Answers (2)

Naomi
Naomi

Reputation: 5486

the new call is actually creating 1 big chunk of memory. It is only indexed as a 2-dimensional array. you can just call delete[] q_1_matrix; (without the for loop).

Upvotes: 3

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385098

The question you refer to restricts answers to using new, but you almost certainly don't need new.

It is far simpler to use the standard library; then, all your worries go away:

std::vector<std::vector<double>> myvec(SPACE, std::vector<double>(TIME));

And if you instead wrap a std::vector<double>(SPACE*TIME) in a class that simulates 2D indexing, so much the better.

Anyway, if you really must manage memory yourself, recall that you're creating one big chunk of dynamic memory here (with the type and dimensions of a double[SPACE][TIME]), so you must free it only once:

delete[] q_1_matrix;

Upvotes: 3

Related Questions