Stefano
Stefano

Reputation: 3258

Dynamic allocated array is not freed

I'm using the code above to dynamically allocate an array, do some work inside the function, return an element of the array and free the memory outside of the function. But when I try to deallocate the array it doesn't free the memory and I have a memory leak. The debugger pointed to the myArray variable shows me the error CXX0030. Why?

struct MYSTRUCT
{
    char *myvariable1;
    int myvariable2;
    char *myvariable2;

    ....
};

void MyClass::MyFunction1()
{
    MYSTRUCT *myArray= NULL;

    MYSTRUCT *myElement = this->MyFunction2(myArray);

    ...

    delete [] myArray;
}

MYSTRUCT* MyClass::MyFunction2(MYSTRUCT *array)
{
    array = (MYSTRUCT*)operator new(bytesLength);

    ...

    return array[X];
}

Upvotes: 1

Views: 167

Answers (3)

Rob Kennedy
Rob Kennedy

Reputation: 163357

The only time you should use delete[] is when you've allocated with new[], but that's not what you're doing. You're using operator new, which isn't what you should use for general-purpose array allocation. Use new[] instead. Or use a vector.

Furthermore, although you pass myArray to MyFunction2 as array and then assign a new value to array inside the function, that doesn't change the value of myArray in the caller. That variable retains its original null value, so your delete[] call does nothing. You can change array to be passed by reference instead of by value so changes to it will be reflected in its actual parameter in the caller.

Upvotes: 5

James Kanze
James Kanze

Reputation: 154047

You allocate the array in MyFunction2, but you don't return its address. The argument to MyFunction2 is by value, so you pass a copy of myArray to it when you call it, but the function itself can never change the value of the caller's local variable.

The simple and obvious answer to your problem is to declare the parameter of MyFunction2 to be a reference, e.g.:

MYSTRUCT* MyClass::MyFunction2(MYSTRUCT*& array)...

A much better solution, however, would be to use std::vector, and not worry about the deallocations.

Upvotes: 3

Michael Krelin - hacker
Michael Krelin - hacker

Reputation: 143299

You allocate the array inside of MyFunction2 and never free it. And in the MyFunction1 you delete[] the null pointer, which is a no-op. I'm not sure I can tell you what you should've done instead, because your intentions aren't clear.

Upvotes: 1

Related Questions