Something I stumbled upon and made me wonder.
Why does this work?
void foo (int* a)
{
int x = 3;
*a = x;
}
int main()
{
int a;
foo(&a);
return 0;
}
But this causes a segmentation fault (both on Visual Studio 2008 and gcc)?
void foo (int* a)
{
int x = 3;
*a = x;
}
int main()
{
int* a;
foo(a);
return 0;
}
Is it something defined in the language or just an implementation issue?
When you declare
You are declaring a pointer variable
abut you are not making it point to anything. Then in the function, you doWhich dereferences the pointer and tries to assign what it points to the value of
x. But since it doesn’t point to anything, you get undefined behaviour, manifested in a segmentation fault.You should do this:
The difference between that and the first one is that
int a;declares a real integer variable, then you take its address with&aand passes it to the function. The pointerainside the functionfoopoints to the variableainmain, and so dereferencing it and assigning to it is perfectly fine.