Hi all, I'm new to the forum and to C++.
I'm studying pointer from the tutorial.
But there is an unexpected behavior I can't understand.
The following code works as It is supposed to do.
1 2 3 4 5 6
void * b;
int * c;
c = (int *) b;
*c = 6;
int d = *c;
cout << "int * c = " << c << "--" << "*c =" << d << endl;
But if I try to have some output using cout:
1 2 3 4 5
void * b;
int * c;
c = (int *) b;
*c = 6;
cout << "int * c = " << c << "--" << "*c =" << *c << endl;
at run-time a segmentation fault is the result.
Does anyone know why?
Thank you in advance.
neither b nor c is pointing to anything in particular. in line 6 (*c = 6), you're de-referencing an uninitialised pointer.
A pointer holds an address, so when you do "*c = 6", you're storing c at the address held in c. Since c is holding some random address, you've stored 6 at some random location in memory. The effect of this could be anything, from setting to your house on fire to seemingly working fine.
Always initialise your variables before using them.
You may say, "Aha! I initialised it (c = (int *b))" Well, you never initialised b, so initialising something with an uninitialised something else just means they are both equally uninitialised.
1 2 3 4 5 6 7 8 9 10 11 12 13
int y; // compiler creates storage for sizeof(int) bytes and names it y, y is uninitialised and contains some random value
int x = 0; // compiler creates storage for sizeof(int) bytes and names it x. x is initialised and contains 0;
int *c = &x; // c now holds the address of x;
*c = 12; // c still holds address of x, x now holds value 12
int *b; // b is uninitialised and points to some random location in memory
*b = 12; // we've dereferenced uninitialised pointer (what you did), prepare for the fire brigade
int *a = &y; // a now holds the address of y - a is initialised, but remember y is not, y is a nonsense value
cout << *a; // this is fine, but we'll get whatever random value is in y
y++; // legal, but not okay, we have no idea what the value of y is
*a = 17; // y is now 17
int *g; //uninitialised pointer g is a variable that holds a nonsense address
cout << g; // is okay, this the value of g
cout << *g; // is not okay, as this would require access to a nonsense address (*g)
Or: int * p = nullptr;
The nullptr is not a valid address either, but it is possible to test whether the address is nullptr or not, while there is no way to tell between a nonsense random number and a valid address.
There's no special knowledge of the inner workings of the compiler needed here.
In your first snippet, b doesn't hold a meaningful address, because you haven't assigned it one.
The comment in your second snipped is incorrect. b doesn't hold a random address. It holds the address of a - because you've assigned it the address of a.