I think this should be a memory leakage. Anyone agree?

Z

Zongjun Qi

#include <iostream>
using namespace std;

class String{
public:
char *Str;
String(){
Str = new char[10000000];
}

~String(){
delete Str;
}
};

int main(){
String my1;
for(int i=0; i< 100000; i++){
String my2;
my2 = my1;
}
return 0;
}


-------------------------
Because inside the constructor, a new memory is allocated each time a
new object is created. And inside the for loop, my2.Str is repointed to
my1.Str, and thus the memory orginally allocated for my2 will be
"lost".

And if we run on Linux, the host should be expected to memory drained
to dry. But it didn't on my box. Wonder why...
 
V

Victor Bazarov

Zongjun said:
#include <iostream>
using namespace std;

class String{
public:
char *Str;
String(){
Str = new char[10000000];
}

~String(){
delete Str;

Undefined behaviour. If the pointer is allocated using 'new[]', it
has to be disposed of using 'delete[]'.
}
};

int main(){
String my1;
for(int i=0; i< 100000; i++){
String my2;
my2 = my1;
}
return 0;
}


-------------------------
Because inside the constructor, a new memory is allocated each time a
new object is created. And inside the for loop, my2.Str is repointed
to my1.Str, and thus the memory orginally allocated for my2 will be
"lost".

Not only that, but 'my2' is destructed at the end of every loop, which
makes the memory allocated in 'my2' to be deleted more than once. Even
if you replace 'delete Str' with 'delete[] Str', the behaviour is going
to be undefined due to multiple deletion of the same pointer.
And if we run on Linux, the host should be expected to memory drained
to dry. But it didn't on my box. Wonder why...

Because the program has undefined behaviour, that's why.

V
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,021
Latest member
AkilahJaim

Latest Threads

Top