#1
  1. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    6
    Rep Power
    0

    Question Segmentation Fault?


    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>

    main() {
    int *d;
    int j;
    int k=3;

    for(j=0;j<k;j++) {
    *(d+j)=j;
    printf("%d\n",*(d+j));
    }
    }


    Why do I get segmentation fault? Thanks!





    :confused: :confused:
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,145
    Rep Power
    2222
    The pointer, d, needs to point to something before you can use it. Since it starts off containing garbage, it's most likely pointing outside of the program's memory space. Trying to access a location outside your memory space causes a segmentation fault.

    If you intend it to point to an array of three integers, then either declare d as an array or assign it some dynamic memory with malloc or calloc.

    Another suggestion: you should declare main's return type explicitly. As you have written it, C assumes that main will return an int, but you have not provided a return statement.
  4. #3
  5. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    6
    Rep Power
    0
    Thank you very much for your help. After assigning memory with malloc to d, it works very well. Thanks a lot!
  6. #4
  7. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    6
    Rep Power
    0

    Question


    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>

    main() {
    int *d;
    int j;
    int k=10000;

    d=(int *)malloc(sizeof(int));

    for(j=0;j<k;j++) {
    realloc(d,(j+1)*sizeof(int));
    *(d+j)=j+1000;
    }

    for(j=0;j<k;j++) {
    printf("%d\n",*(d+j));
    }
    return(1);
    }


    I have one more question. Should I realloc memory everytime in the for loop? If k is very big, how is it efficient? Thanks!


    :confused:
  8. #5
  9. No Profile Picture
    Senior Slacker
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Location
    Houston, TX
    Posts
    30
    Rep Power
    12

    Why realloc at all?


    Since you already know the size of k(in your example its 10000) why not just malloc the memory to begin with instead of reallocing in your for loop and one each time......

    Since realloc may have to move the memory block each time it probably isn't a wise option for performance......

    PHP Code:
    d=(int *)malloc(sizeof(int) * k); 
    Cya,

    Jim
  10. #6
  11. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2003
    Posts
    6
    Rep Power
    0
    Thanks for your information. It is helpful.

IMN logo majestic logo threadwatch logo seochat tools logo