Reputation: 911
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?
Upvotes: 1
Views: 177
Reputation: 61
int a;
Assigns memory as soon as you declare it but this not the case with int *a;
int *a;
is pointer declaration (MEMORY not yet allocated for that).
int *a = (int*)malloc(sizeof(int)); // allocate memory
Upvotes: 2
Reputation: 75130
When you declare
int* a;
You are declaring a pointer variable a
but you are not making it point to anything. Then in the function, you do
*a = x;
Which 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:
int i; // the actual integer variable
int* a = &i; // a points to i
The difference between that and the first one is that int a;
declares a real integer variable, then you take its address with &a
and passes it to the function. The pointer a
inside the function foo
points to the variable a
in main
, and so dereferencing it and assigning to it is perfectly fine.
Upvotes: 4