When i pass a pointer to a function and then change the pointer to a another location of the memory, I get SIGSEV or garbage values. Where is a code to demonstrate that:
#include <stdio.h>
void fn(char *n) {
/*
* imagine this variable 'b' is
* a part of a structure of
* some library
*/
char *b = "hello, world!";
n = b;
}
int main() {
char *a = NULL;
fn(a);
/* it throws garbage or SIGSEV */
printf("%s\n", a);
}
I know what's the reason for this problem. The function fn
, when called creates a variable b
but when fn
ends, b
is deleted. And therefore, a
is pointing to a memory that the program doesn't own. What do I do to fix this program. I know, I can solve the issue just by using C++ with it's std::string. But I have to do it in C.
Thanks.
It means that you need to pass the pointer a
defined in main
to the function fn
by reference. In C passing by reference means passing an object indirectly through a pointer to it. Thus dereferencing the passed pointer the function will have a direct access to the object pointed to by the pointer and can change it.
void fn(char **n) {
/*
* imagine this variable 'b' is
* a part of a structure of
* some library
*/
char *b = "hello, world!";
*n = b;
}
And in main you need to write
fn( &a );
Pay attention to that the pointer a
will be valid after the function call because it points to a string literal used in fn
and string literals have static storage duration.