Reputation: 1849
I'm just playing around c++ to understand how the memory leak occurs.
% g++ --version
Apple clang version 11.0.0 (clang-1100.0.33.17)
Target: x86_64-apple-darwin19.3.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin
Consider the code below
int main() {
const int c=10000;
int* ptrs[c];
for (int n=0; n<c; n++) {
int s=1000;
int *x = new int[s];
for (int i=0; i<s; i++){
x[i] = i*10;
}
ptrs[n] = x;
//delete[] x; // <-- (1)
}
//Print pointers
for (int n=0; n<c; n++) {
std::cout << ptrs[n] << std::endl;
//delete[] ptrs[n]; // <-- (2)
}
std::getchar();
return 0;
}
When I check the program memory usage through the task manager at the point where program reaches std::getchar()
I see that it uses ~360KB
memory when I free up space with delete[] x;
and ~7.6MB
when doing it by delete[] ptrs[n];
. My question is why does the second method consume more memory than the first one? They are technically doing the same thing aren't they?
Upvotes: 0
Views: 95
Reputation: 62694
In the first case, you have implementation defined behaviour, because you inspect a pointer after having called delete[]
on it. Notwithstanding that, you only have 1000 int
s in dynamic storage at a time.
In the second case, you have 10000000 int
s in dynamic storage at the point where you start printing values.
It is likely that your implementation is re-using the same memory over and over.
Upvotes: 1