I have no idea why this is happening since the variable is not interacting with anything else in the program.
This is a sign of undefined behavior. The variable is not directly interacting with anything else, but it is present in the program. That can be enough to change how the compiler deals with undefined behavior, potentially changing a silent no-op into a crash.
[In your case, there is undefined behavior when you use the value of a variable before assigning a value to that variable. Specifically, int *p1;
declares a variable without assigning a value to it, and the "*p1
" in the next line uses the value of p1
(to get the address to where the value of firstValue
is copied). Similarly, no value has been assigned to firstValue
at that point, so you get another bit of undefined behavior in the same assignment. Realistically, though, it's the uninitialized pointer that causes the segmentation fault.]
Relying on something like declaring a new variable to reveal undefined behavior is not a great plan. A better plan would be to turn on all of your compiler's warnings. The warnings may miss some instances of undefined behavior, but they will catch a significant portion of them. Serious projects often require all (or at least -Wall
) warnings to be checked; code that does not compile warning-free is quickly rejected. So you might as well learn to code warning-free now.