Emil berg
Emil berg

Reputation: 15

Why does this lead to an segmentation fault in C

I try to put my pointer to the parameter passed it, but it leads to a segmentation fault

#include <stdio.h>

void putPointer ( int *point, int num ) {
    point = &num;
}

int main(void) {

    int a = 42;

    int *p;
    // p = &a
    putPointer( p, a );

    printf( "%d\n", *p );

    return 0;
}

Upvotes: 0

Views: 52

Answers (3)

prog-fh
prog-fh

Reputation: 16785

In putPointer() you try to assign point but point is a copy of p, thus p is left unchanged. Since p is still not initialised, it could access any address and *p causes a seg-fault.

You could actually change p by expecting int **point_ptr as parameter, passing &p and performing *point_ptr=&num; but you would encounter another problem. Actually, num will disappear as soon as the function returns, so keeping its address in p is incorrect: num does not exist anymore when using *p.

Upvotes: 2

MikeCAT
MikeCAT

Reputation: 75062

Arguments in C are copies of what are passed, so p in the main() function remains uninitialized after putPointer(p,a);. Using values of uninitialized non-static local variables, which are indeterminate, invokes undefined behavior.

Also note that you shouldn't take out pointers to non-static local variables (including function arguments) on returning from functions and must not use these pointers after returning from functions because non-static local variables are invalidated on returning.

Upvotes: 2

peanutbatterballs
peanutbatterballs

Reputation: 153

&num

will be the address of num on the stack. You are trying dereference the stack in printf("%d\n", *p);.

Upvotes: 0

Related Questions