After implementing the C++ code below, I ran valgrind --leak-check=full
in order to check if there was any memory leak. The result was 0 bytes were in use at exit and no leaks are possible.
However, later I discovered that I've forgotten to use delete[] x
instead of just delete x
inside the destructor.
I searched for some explanations (for instance: delete vs delete[] operators in C++), and everything I read said that using delete
without []
can cause memory leak, since it calls just the destructor for the first object in the array.
I changed the code to delete[] and the valgrind output was the same (as expected). But now I'm confused: "Is there a problem with valgrind, or does delete
really works fine for arrays even without the operator []
?"
#include <iostream>
#include <string.h>
using namespace std;
class Foo {
private: char *x;
public:
Foo(const char* px) {
this->x = new char[strlen(px)+1];
strcpy(this->x, px);
}
~Foo() {
delete x;
}
void printInfo() { cout << "x: " << x << endl; }
};
int main() {
Foo *objfoo = new Foo("ABC123");
objfoo->printInfo();
delete objfoo;
return 0;
}