I want to transfer few variables using structure. Following is the sample program code. When I run this program, I get segmentation fault. I use gcc compiler.
Can anyone help me with this?
struct data{
const char * ip;
const char * address;
const char * name;
};
int fun(struct data *arg) {
//struct data *all;
const char *name = arg->name;
printf("\n My name is:%s",name);
return 1;
}
int main(int argc, char * const argv[]) {
struct data * all;
int k=0;
//data.name = argv[1];
all->name=argv[1];
k = fun(all);
printf("\n k is:%d ",k);
return 0;
}
The problem is here:
You have not allocated memory for
all. When you have an uninitialized pointer, it is pointing to random locations in the memory, which you probably won’t have access to. You have two options:Allocate on the stack:
Allocate on the heap:
The first case is good when you know that
allwill be needed only in the current function (and those you call). Therefore, allocating it on the stack is sufficient.The second case is good for when you need
alloutside the function creating it, for example when you are returning it. Imagine a function initializingalland return it for others to use. In such a case, you can’t allocate it on the stack, since it will get destroyed after the function returns.You can read more about it in this question.