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?