This would be two questions in one
I have two pieces of codes, the only difference being the order between the declaration of int* a; and int cpt = 0; on lines 6 and 7.
Case 1:
#include <iostream>
using namespace std;
int main()
{
cout<<"begin"<<endl;
int* a;
int cpt = 0;
cout<<"after init "<<a<<endl;
*a = 2;
cout<<"after assign"<<endl;
cout<<a<<" "<<*a<<endl;
cout<<"after cout"<<endl;
int* b;
*b = 2;
cout<<b<<" "<<*b<<endl;
}
Output:
begin
after init 0x7fff6c97f05e
Bus error: 10
Case 2:
#include <iostream>
using namespace std;
int main()
{
cout<<"begin"<<endl;
int cpt = 0;
int* a;
cout<<"after init "<<a<<endl;
*a = 2;
cout<<"after assign"<<endl;
cout<<a<<" "<<*a<<endl;
cout<<"after cout"<<endl;
int* b;
*b = 2;
cout<<b<<" "<<*b<<endl;
}
Output:
begin
after init 0x7fff50e4ac00
after assign
0x7fff50e4ac00 2
after cout
Segmentation fault: 11
I'm wondering why the declaration order affects the error. The cpt variable isn't used anywhere, so why would it's declaration affect the error?
I'm also wondering why does the pointer "a" in the second case doesn't produce a segfault when referencing it when the "b" pointer does produce a segfault. They have the same declaration and same usage, why the difference?
Thanks!
The key is what you're doing (dereferencing an uninitialized pointer) results in undefined behavior, so you really can't expect anything in particular to happen, nor is there a reasonable/"standard-conformant" explanation for what the program does. It can be, however, the case, that the stack is set up in a way that in the second case, a
points to a valid memory location by accident, but that's just a guess.