Hello stackoverflow community, I was studying pointers in C++. I have a little bit of background in golang and python but not in C or C++, so forgive me because of my flawed understanding. Let me post the piece of code that is working fine and is giving segfault.
- 1
This one prints 5
int var = 5;
int *p = &var;
cout << *p << endl;
- 2
This one also prints 5
int *p;
p = &var;
cout << *p << endl;
prints 5
(because p is a pointer to int and address of var is a pointer to int. ).
However,
- 3
This one segfaults.
int *p;
*p = var;
cout << *p << endl;
which I assume happens because I am assigning an integer variable to a variable which is supposed to be a pointer to the integer. Why was it not showing incompatible type error at compile time rather than giving a segmentation fault? What is the program trying to do that is giving a segmentation fault, and how?
and
- 4
This one also segfaults
int *p;
*p = 5;
cout << *p << endl;
throws a segfault as well. My understanding for the above code is, I declared a pointer to int, and I am assigning an integer value to a de-referenced pointer to integer, but since the variable is not initialized, the compiler haven't assigned the memory on the stack for storing the value (something like a dangling pointer behaviour?) If that is the reason, why is it throwing a segmentation fault, the reason for that error being accessing memory outside the program's reach?
- If a variable is declared only and not initialized, does the compiler ignores the variable name totally and treats it as a non-existant variable name?
Thank you.