0

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;
}
Nathan Fellman
  • 122,701
  • 101
  • 260
  • 319
NLander
  • 35
  • 1
  • 4
  • This is C: malloc your pointers. By declaring a pointer you're not allocating memory for it automatically. – m0skit0 Jul 18 '12 at 09:57

3 Answers3

3

The problem is here:

struct data * all;
all->name=argv[1];

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:

  1. Allocate on the stack:

    struct data all;
    all.name=argv[1];
    k = fun(&all);
    
  2. Allocate on the heap:

    struct data *all = malloc(sizeof(*all));
    if (all != NULL)
    {
        all->name=argv[1];
        k = fun(all);
    }
    free(all);
    

The first case is good when you know that all will 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 all outside the function creating it, for example when you are returning it. Imagine a function initializing all and 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.

Community
  • 1
  • 1
Shahbaz
  • 46,337
  • 19
  • 116
  • 182
  • Thank you very much. This information not only worked my current problem but also helped me through my basic concepts. :) – NLander Jul 18 '12 at 19:38
3

You need to allocate memory and assign it to the pointer all:

struct data * all;   
int k=0;
all = malloc(struct data);

all->name=argv[1];
k = fun(all);
//...
free(all);

or use a local struct and pass its pointer to the function:

struct data all;   
int k=0;

all.name=argv[1];
k = fun(&all);
MByD
  • 135,866
  • 28
  • 264
  • 277
2

all is a pointer to type struct data. You never assigned it, so it doesn't point to anything.

You need to do one of the following:

  • allocate all on the stack:

    struct data all;

  • allocate all on the heap:


    struct data* all = malloc(sizeof (struct data));   
    // don't forget to check if the allocation succeeded, 
    //and don't forget to free it when you're done
Nathan Fellman
  • 122,701
  • 101
  • 260
  • 319