[Solved] The segmentation fault error that I cannot understand [duplicate]


Here’s a step-by-step breakdown of what your code is doing:


int *a;
int *b;

This declares two pointers to int named a and b. It does not initialize them. That means that their values are unspecified, and you should expect them to be complete garbage. You can think of them as “wild” pointers at this moment, which is to say that they don’t point to valid objects, and dereferencing them will cause Undefined Behavior and introduce a plethora of weird bugs, if not a simple crash.


int c=12;

This creates a simple local variable c of type int, which is initialized, with a value of 12. If you hadn’t initialized it, as in int c; then it would also be full of garbage.


a=&c;

This snippet sets the pointer a to point to c, which is to say that the address of c is assigned to a. Now a is no longer uninitialized, and points to a well-defined location. After this, you can safely dereference a and be assured that there is a valid int at the other end.


*b=*b;

Here, you are dereferencing b, which means that you are reaching into your programs memory to grab whatever is pointed to by b. But b is uninitialized; it is garbage. What is it pointing to? Who knows? To read from the address it points to is like Russian roulette, you might kill your program immediately if you get really unlucky and the Operating System or runtime environment notices you doing something that’s obviously wrong. But you also might get away with it, only for weird and unpredictable bugs to emerge later. This weirdness and unpredictability is why a good C++ programmer avoids Undefined Behavior at all costs, and ensures that variables are initialized before they are used, and makes sure that pointers are pointing to valid objects before dereferencing them.

Why does there appear to be a difference depending on a=&c;?

As to why your program apparently crashes or doesn’t crash depending on how you initialize the other pointer, the answer is that it doesn’t matter. In both cases, you’re causing Undefined Behavior; you are breaking the language’s rules and you should not expect the language to behave correctly for you thereafter, and all bets are off.

0

solved The segmentation fault error that I cannot understand [duplicate]