Reputation: 15
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 = #
}
int main(void) {
int a = 42;
int *p;
// p = &a
putPointer( p, a );
printf( "%d\n", *p );
return 0;
}
Upvotes: 0
Views: 52
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=#
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
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
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