Juan Manuel
Juan Manuel

Reputation: 51

Deleting an array created by a function

I'm making a tool to solve this although I got massively sidetracked by the code itself.

In various places I have functions that return (pointers to) arrays. Most times those functions are recursive and the array created in the inner call may be useless later.

I tried to use delete[]; even though the compiler didn't complain and the program ran fine I could see that a huge ammount of memory was being allocated. The code looked something like this:

template <typename Type> Type* foo(unsigned short size,...)
{
    //...
    Type *tmp;
    //...
    tmp=foo(param,...);
    //...
    delete[] tmp;
    //...
}

I then asked myself if, when the array was created out of scope, delete[] actually deleted all the allocated memory or just the first index (or nothing at all?).

I rewrote that piece of code to look like this:

template <typename Type> Type* foo(unsigned short size,...)
{
    //...
    Type *tmp;
    //..
    tmp = new Type[i];
    tmp = foo(param,...);
    //...
    delete[] tmp;
    //...
}

Memory consumption lowered, however I quickly realized that the array I created just before calling foo(...) wasn't actually deleted... ever.

So lastly I tried:

template <typename Type> Type* foo(unsigned short size,...)
{
    //...
    Type *tmp, *dump;
    //..
    dump = tmp = new Type[i];
    tmp = foo(param,...);
    delete[] dump;
    //...
    delete[] tmp;
    //...
}

But I was just moving the issue one step further, and in the process creating yet another array. Unsurprisingly (although not really) memory consumption skyrocketed.

Questions here are:

I don't really want to use std::vector because rewriting all the pertinent code seems like a major task, and because, as a rookie, I kind of feel better knowing that I did not need a library's help to write my program (obviously I still use them; I can't imagine what goes into writing something like <iostream> for example).

PS: My code on GitHub.

PPS: I apologize for my english; not a native speaker.

Upvotes: 0

Views: 95

Answers (1)

marcinj
marcinj

Reputation: 49976

What is the correct way to do this?

You should pair new T[] with delete[] - no magic here. To make sure you do it right use std:unique_ptr<T[]> - version for arrays. Or - std::vector, but you said you dont like it.

Why did memory consumption lowered with the first change?

seems ilogical, you allocated more memory and it dropped....

I took a look at your github project and I found this:

delete[] slhs, srhs;                //Deletes the now useless sorted arrays.

delete[] does not list delete arrays, as far as I remember only srhs will get freed. You should write:

delete[] srhs;
delete[] slhs;

find other places like this, or use std::unique_ptr<>

Upvotes: 1

Related Questions