0

Suppose we want to create a class / struct which contains an object, and repeatedly replace a pointer to an object of that class / struct with a new instance of it.

struct foo {
    int a[128];
};

int main() {
    foo* bar;

    for(int i = 0; i < 120000; i++) {
        delete bar;
        bar = new foo();
    }

    return 0;
}

This program works, as far as I can tell, and successfully frees up the memory used by 'a' at the deletion of 'foo' (Task Manager tells me it uses about 14.5 MB of RAM). But instead of declaring it this way, let's say we need a dynamic object instead:

struct FOO {
    int* A;
    FOO() {
        A = new int[128];
    }
};

int main() {
    FOO* BAR;

    for(int i = 0; i < 120000; i++) {
        delete BAR;
        BAR = new FOO();
    }

    return 0;
}

In this case, the program does not seem to successfully free up the memory stored at 'A' (Task Manager tells me this uses about 78.1 MB of RAM). Why does the call to delete BAR fail to free the memory at 'A', and how can this code be reconfigured so that that can be done?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
MCosmo
  • 13
  • 1

2 Answers2

-1

What you are missing is destructor in Foo struct. See this variant :

struct FOO {
int* A;
FOO() {
    A = new int[128];
}
~FOO()
{
    delete A[];
}
};

int main() {
FOO* BAR;

for(int i = 0; i < 120000; i++) {
    delete BAR;
    BAR = new FOO();
}

return 0;
}

The destructor of FOO should now take care of deleting the memory created dynamically in the constructor.

-1

You need to implement the destructor to free the memory allocated inside constructor. However, memory allocation inside constructor is a bad idea and there are better alternatives to it.
Also, since you are dealing with pointers, please make sure you are checking memory allocation result and properly assigning NULL as and when required along with checking if it is safe to delete the pointer
Note1: since you have used new to allocate array, you have to use delete[] rather than delete.
Note2: You also started deleting the BAR even before allocating.
It should look at least something like this:

    struct FOO {
    int* A;
    FOO() {
        A = new int[128];
    }
    ~FOO() {
         if(A) delete[] A; // use delete[] instead of delete for an array
         A = nullptr;
    }
};

int main() {
    FOO* BAR;
    BAR = new FOO();
    for(int i = 0; i < 120000; i++) {
        if( BAR) {
            delete BAR;
            BAR = nullptr;
        }
        BAR = new FOO();
    }

    return 0;
}
Abhinav
  • 1,496
  • 3
  • 15
  • 31