I helped my friend with debugging a code, problematic part was something like that:
class MyClass {
char * text;
public:
MyClass(const char * c) {
if (c != nullptr) {
text = new char[strlen(c)];
strcpy(text, c);
}
else
text = nullptr;
}
~MyClass() {
delete[] text;
}
};
int main() {
MyClass foo("bar");
return 0;
}
Of course problem is with strlen(c)
, should be strlen(c) + 1
. Anyway, what surprised me, why did that result in heap corruption error in the moment of calling delete[] in destructor? What caused it?
This error is thrown by debugger, my question is: Why did this error popped up at the moment of freeing memory, not earlier? It would be much easier to find any bugs in code this way.
@edit old c = nullptr -> text = nullptr There was this bug I wrote accidentally, (sorry, I didn't notice, now it is what I meant). The thing is, it was forbidden to use strings in this task, so it had to be done C-way. Sorry for so many edits. I really have to learn how to ask precise questions.