segmentation fault

Discussion in 'C Programming' started by ramu, Nov 6, 2006.

  1. ramu

    ramu Guest

    While am trying to run this code am getting segmentation fault.
    What's wrong with this code?
    Here am trying to assign a value to the variable b.

    #define SIZE 10

    struct y {
    int a;
    struct x {
    int b;
    } *c[SIZE];
    } d;


    d.c[SIZE] = malloc(10 * sizeof(struct x));

    ramu, Nov 6, 2006
    1. Advertisements

  2. ramu

    Chris Dollin Guest

    [Horrid names. I assume they're just for illustration.]
    BOOM. `d.c` has only SIZE elements, indexed from 0 to
    `SIZE - 1`. So your code has already broken. And you
    didn't #include stdlib.h, so your use of `malloc` is
    broken too. (Didn't your compiler complain about that?)

    It's quite possible that this didn't cause your problem,
    You haven't assigned to `d.c[0]`. Since `d` is static,
    its elements are initialised to zero. So `d.c[0]` is
    a null pointer. You've tried to assign to a field of
    a structure the null pointer doesn't point to.

    BOOM. Very likely the point at which you get your
    Chris Dollin, Nov 6, 2006
    1. Advertisements

  3. ramu

    mark_bluemel Guest

    I think you are trying to dynamically allocate the array of SIZE
    pointers to struct x items here. It won't work.

    Depending on what you are trying to achieve, you could do this :-

    int i;
    for (i = 0;i < SIZE;i++) {
    d.c = malloc(sizeof(struct x));
    } /* error handling is missing */

    still remembering that you can only access from d.c[0] to d.c[SIZE -
    1], so you could do

    d.c[10]->b = 42;

    or you could change the structure declaration

    struct y {
    int a;
    struct x {
    int b;
    } *c;
    } d;
    d.c = malloc(sizeof(struct x) * SIZE);
    /* or d.c = calloc(SIZE, sizeof(struct x));
    * again error handling is missing
    d.c[SIZE - 1].b = 42;

    I'll now stand back and let others find the holes in what I've
    suggested :)
    mark_bluemel, Nov 6, 2006
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.