简体   繁体   中英

C++ Class pointer dynamic array deallocate problem

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

#define ROW 1

class Foo
{
public:
    Foo()
    {
        this->dummy = new unsigned int[100];
    }
    ~Foo()
    {
        delete[] this->dummy;
        this->dummy = NULL;
    }

    unsigned int* dummy;
};

Foo** allocate()
{
    Foo** foo_array = NULL;
    foo_array = new Foo * [ROW]; //Create space for Foo addresses (row)

    for (int i = 0; i < ROW; i++)
        foo_array[i] = new Foo; //Create and allocate Foo for each address space(col)

    return foo_array;
}

int deallocate(Foo* foo_array[ROW])
{
    if (foo_array != NULL)
    {
        for (int i = 0; i < ROW; i++)
            delete foo_array[i];
        delete[] foo_array;
        
        foo_array = NULL;

        return 1;
    }

    return 0;
}

void main()
{
    Foo** foo_array = NULL;

    foo_array = allocate();
    deallocate(foo_array);
    
    if (foo_array != NULL)
        printf("not null something wrong\n");
    system("pause");
}

In main() function, foo_array should be pointed to NULL as soon as the deallocation is performed by the deallocate(Foo* foo_array[ROW]) function.

but, In deallocate(Foo* foo_array[ROW]) function,

foo_array = NULL;

It seems point to NULL by above syntax, however in main() function, foo_array is not point to NULL.

so, I tried to change above syntax in deallocate(Foo* foo_array[ROW]) function,

foo_array = NULL; => (*foo_array) = NULL;

It spits out write access violation errors.

Where did it go wrong?

The correct syntax would be foo_array = deallocate (foo_array); and your deallocate should return NULL .

I don't see any reason to declare foo_array as pointer to pointer. In your code you are passing pointers by value. That means you can change what the pointers are pointing at but you can't change the values of the pointers. You can solve the problem using references.

#include <cstdio>

#define ROW 1

class Foo
{
public:
    Foo()
    {
        this->dummy = new unsigned int[100];
    }
    ~Foo()
    {
        delete[] this->dummy;
        this->dummy = NULL;
    }

    unsigned int *dummy;
};

void allocate(Foo *&foo_array)
{
    foo_array = new Foo[ROW];
}

void deallocate(Foo *&foo_array)
{
    delete[] foo_array;
    foo_array = nullptr;
}

int main()
{
    Foo *foo_array = nullptr;

    allocate(foo_array);
    deallocate(foo_array);
    
    if (foo_array != nullptr)
        printf("not null something wrong\n");
}

Of course you can make your code much simpler using STL containers or smart pointers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM