G
G
Gleb Igumnov2014-09-19 15:20:54
OOP
Gleb Igumnov, 2014-09-19 15:20:54

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;
};

As you can see, there is no call b = new B(); in the class A constructor; that is, no memory is allocated.
However, the program manages to call getFlag() and setFlag() using the pointer to b received from class A (because it was not even initialized to 0, it is clear that it leads somewhere) and get values ​​from them. Moreover, when b->serialize() is called, the debug print that is in this function will be issued until the flag is called, on which the program finally crashes with a segfault. Moreover, this is not an isolated case, several dozen objects of class A are created, and only occasionally, not in every launch, when accessing A::b of any of them, the program crashes.
Moreover, if the program is debugged in gdb, then everything, as it should be, falls with segfault at the first attempt to do something with A::b.
Tell me, what can cause such a strange behavior of the program? (I naturally already added memory allocation, but the theoretical interest remained)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vyacheslav, 2014-09-19
@CrazySage

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 question

Ask a Question

731 491 924 answers to any question