Search code examples
cpointersreallocansi-c

Segmentation fault on realloc ANSI C


If I run this code is shown to me "segmentation fault", but if in the "for" of the "create" function I set the clause i <1 (ie one cycle), the program is working, why?

void create(char ***a,int *length){
    int i=0;
    *length = 0;
    for(i=0;i<4;i++){
        ++(*length);
        (*a)=realloc(*a,(*length)*sizeof(char *));
        *(a[i])="Hello\0";
    }
}

int main(int argc, char *argv[]) {
    int i;
    char **a = NULL;
    int *l = malloc(sizeof(int));
    create(&a,l);
    for (i=0; i<(*l); i++) {
        printf("%s",a[i]);
    }
    printf("\n");
    return EXIT_SUCCESS;
}

what I would like is that at the end, the program show me 4 times "Hello"


Solution

  • This

    *(a[i]) = ...
    

    should be

    (*a)[i] = ...
    

    A "string" literal like "Hello" already implicitly adds a terminating '\0' character. So there is no need to specify it explicitly like in here: "Hello\0".