Below, I have provided three different scenarios in which the codes spit out "segmentation fault" and I am not sure why! Scenario 1 only performs the first line (This is i: 42
) and then it crashes with the segmentation fault message. In scenario 2, where I just declare the pointers (but do not initialise them), the code works up to std::cout << "This is *pi3: " << *pi3 << std::endl;
(it does not perform this line and the rest). Finally, in scenario 3, once again it only performs the first line (i.e. "This is i: 42") even though I only added int j = 5;
!
Scenario 1:
#include <iostream>
#include <cstdlib>
int main(){
int i = 42;
int *pi = nullptr;
int *pi2 = &i ;
int *pi3 = nullptr;
std::cout << "This is i: " << i << std::endl;
std::cout << "This is *pi: " << *pi << std::endl;
std::cout << "This is pi: " << pi << std::endl;
std::cout << "This is *pi2: " << *pi2 << std::endl;
std::cout << "This is pi2: " << pi2 << std::endl;
std::cout << "This is *pi3: " << *pi3 << std::endl;
std::cout << "This is pi3: " << pi3 << std::endl;
pi3 = pi2;
std::cout << "This is *pi3: " << *pi3 << std::endl;
std::cout << "This is pi3: " << pi3 << std::endl;
return 0;
}
Scenario 2:
#include <iostream>
#include <cstdlib>
int main(){
int i = 42;
int *pi ;
int *pi2 = &i;
int *pi3 ;
std::cout << "This is i: " << i << std::endl;
std::cout << "This is *pi: " << *pi << std::endl;
std::cout << "This is pi: " << pi << std::endl;
std::cout << "This is *pi2: " << *pi2 << std::endl;
std::cout << "This is pi2: " << pi2 << std::endl;
std::cout << "This is *pi3: " << *pi3 << std::endl;
std::cout << "This is pi3: " << pi3 << std::endl;
pi3 = pi2;
std::cout << "This is *pi3: " << *pi3 << std::endl;
std::cout << "This is pi3: " << pi3 << std::endl;
return 0;
}
And Scenario 3 (where I just add int j = 5;
):
#include <iostream>
#include <cstdlib>
int main(){
int i = 42;
int j = 5 ;
int *pi ;
int *pi2 = &i;
int *pi3 ;
std::cout << "This is i: " << i << std::endl;
std::cout << "This is *pi: " << *pi << std::endl;
std::cout << "This is pi: " << pi << std::endl;
std::cout << "This is *pi2: " << *pi2 << std::endl;
std::cout << "This is pi2: " << pi2 << std::endl;
std::cout << "This is *pi3: " << *pi3 << std::endl;
std::cout << "This is pi3: " << pi3 << std::endl;
pi3 = pi2;
std::cout << "This is *pi3: " << *pi3 << std::endl;
std::cout << "This is pi3: " << pi3 << std::endl;
return 0;
}
I understand that initialising pointers (and to a greater extend all variables) is good practice. Then, why does it not work here? And why does it only work half way through the code when I do not initialise *pi and *pi3 in scenario 2? I would be thankful if you could explain to me what is happening in each scenario and the source of error(s). I use both g++ and clang++ on a 2019 MacBook Pro!
Thank you.