Answer the question
In order to leave comments, you need to log in
Why can a C++ program work with incorrectly allocated memory?
Good afternoon. A situation arose, the reasons for the appearance of which I want to understand.
I have a C++ program with classes A and B
class A {
public:
A() {}
B* getB() {return b;}
private:
B* b;
};
class B {
public:
B() {};
bool getFlag() {return flag;}
void setFlag (bool f) {flag = f;}
void serialize() {...}//запись в файл
private:
bool flag;
};
Answer the question
In order to leave comments, you need to log in
This is quite possible:
The compiler created an object A and wrote "garbage" into B* b.
"Thinking" that at address *b there is an object of class B, it reads and writes a boolean value somewhere in memory (since the simple methods getFlag and setFlag are most likely optimized for simply accessing the flag attribute and this explains the crash during debugging). When a complex function is called, in fact, a SegFault occurs.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question