1

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?

1
  • You should be getting a warning with the second example. Commented Feb 27, 2012 at 0:52

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Also problematic: printf("%d\n", a);, since "%d" expects type int but a is type int *.
Thanks. The segmentation fault happens even without the printf so I deleted it from the question
@DigitalDa did you not read the top 3/4 of my post? The segmentation fault is not because of the printf, it's because you're creating a pointer that doesn't point to anything and then assigning x to what it points to (which is nothing)
@Seth Carnegie I did. The printf is irrelevant
@DigitalDa no, it's a problem in the program. Just because it doesn't make it crash doesn't mean it's not a problem; you can't use the %d specifier with pointers because pointers and integers may be different sizes. It was the second thing that is incorrect in the second program.
|
2
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 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.