#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    4
    Rep Power
    0

    Copying to element of the structure: Segmentation Fault


    Can you help me with this program? I am getting segmentation fault. And I am sure it is because of the the bold statement.

    #include <stdio.h>

    typedef struct{
    char *data;
    struct node_t *next;
    }node_t;

    int main(){
    node_t *node[8];
    char *p;
    char c = 'a';

    p = &c;
    node[0] = (node_t *)malloc(sizeof(node_t));
    memcpy(node[0]->data, p, 1);
    return 0;
    }
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,892
    Rep Power
    481
    You correctly identified a bad spot. At a glance, I see two troubles. Err, 1 problem.

    Consider

    node[0] = (node_t *)malloc(sizeof(node_t));

    The memory allocated has left over values from whatever was there beforehand. While "random" may not be strictly correct, you may as well think of it that way. Therefore, your pointer to character, data, is an undetermined address.

    typedef struct{
    char *data;
    struct node_t *next;
    }node_t;

    you'd need to allocate space for it as well,
    node[0]->data = malloc(1);

    Comments on this post

    • yedapoda agrees
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    4
    Rep Power
    0
    Thanks. That really helped. Cheers! How silly I was! Actually I am allocating space to only 2 pointers in the structure and not for the data.

    Originally Posted by b49P23TIvg
    You correctly identified a bad spot. At a glance, I see two troubles. Err, 1 problem.

    Consider

    node[0] = (node_t *)malloc(sizeof(node_t));

    The memory allocated has left over values from whatever was there beforehand. While "random" may not be strictly correct, you may as well think of it that way. Therefore, your pointer to character, data, is an undetermined address.

    typedef struct{
    char *data;
    struct node_t *next;
    }node_t;

    you'd need to allocate space for it as well,
    node[0]->data = malloc(1);

IMN logo majestic logo threadwatch logo seochat tools logo