#include<stdlib.h> #include<iostream> using namespace std; int * foo (int a) { int i; int* p; i = a *p = i; return p; } int main(void) { int* q; int b = 10; q = foo(&b); return 0; }The problem with this code is that the pointer
p
is not initialized before it is dereferenced. This will cause a segmentation fault. So if we change *p = i
to p = &i
, the segmentation fault will be gone. A pointer should always be initialized with an address first.
However, there are other problems with the code, depending on the purpose of the function. If the intended outcome is that the returned pointer points to the same value as the input parameter, the code won't work either. After eliminating the segmentation fault, the code is like this:
int * foo (int a) { int i; int* p; i = a; p = &i; return p; }The returned pointer points to the local variable
i
which will be out of the scope once the function returns. Even if we set p = &a
, it won't work, because a
is also a local variable in the scope of function foo
only.
So in main
, q
will not point to b
because when we call foo(b)
, the value of b
is copied to the local variable a
which has a different address than b
.
To get the intended behavior, we need to have something like this:
#include<stdlib.h> #include<iostream> using namespace std; int * foo (int* a) { int* p; cout << "p = " << p << endl; p = a; cout << "p = " << p << endl; return p; } int main(void) { int* q;it should work int b = 10; q = foo(&b); cout << "&b = " << &b << endl; cout << "q = " << q << endl; cout << "b = " << b << endl; cout << "*q = " << *q << endl; return 0; }
No comments :
Post a Comment