Two almost identical C ++ programs, one working well and the other getting a runtime error

Compare the following two code snippets:

1.

#include <iostream>
using namespace std;
class B{
public:
    int val;
};
int main(){
    B *b;
    int t = 0;
    b->val = 1;
    cout << 123 << endl;
    return 0;
}

2.

#include <iostream>
using namespace std;
class B{
public:
    int val;
};
int main(){
    B *b;
    b->val = 1;
    cout << 123 << endl;
    return 0;
}

Both versions are compiled. Code # 1 works well, but code # 2 gets a runtime error.

I compile using C ++ 11 and run a Windows machine.

It really bothers me. Can someone tell me the reason?

+5
source share
5 answers

Both are wrong. The pointer is bnot initialized, so you should not access it through memory.

B *b;
b->val = 1;

So, you were lucky when one of them crashed.

You were unlucky to others, and it did not work.

difficult

You can remove the indirect ...

B b;
b.val = 1;

Or you can highlight it ...

std::unique_ptr<B> b(new B());
b->val = 1;
+14

b->val = 1;

, , : .

undefined (UB), , , .

, , , . , , ++ promises . UB. , .

+4

. , , undefined.

#include <iostream>
using namespace std;
class B{
public:
    int val;
};
int main(){
    B *b = new B();
    int t = 0;
    b->val = 1;
    cout << 123 << endl;
    delete b;
    return 0;
}

,

#include <iostream>
using namespace std;
class B{
public:
    int val;
};
int main(){
    B b;
    int t = 0;
    b.val = 1;
    cout << 123 << endl;
    return 0;
}
+1

, : B* b;. C ++ : .

The solution to your problem is simple: do not use a pointer. B b;will instantiate the class and call its constructor.

Code # 1 works well, but code # 2 gets a runtime error.

In the standard expression, both codes show undefined behavior. This means that almost anything can happen and consists of seeming work (i.e. there may be a mistake, but there is no visible symptom).

+1
source

b->valindicates an invalid memory location. Allocate memory for bbefore assignmentb->val

0
source

All Articles