简体   繁体   中英

c struct pointer array vs struct pointer pointer malloc

works:

struct data{
    int val;
};

int main(void){
    struct data *var[2];
    (*var)->val = 6;
    printf("%d\n", (*var)->val);
    return 0;
}

segfault:

struct data{
    int val;
};

int main(void){
    struct data **var = malloc(3 * sizeof(struct data));
    (*var)->val = 6;   // <- crash
    printf("%d\n", (*var)->val);
    return 0;
}

can someone explain why segfault appears and give me an working example with minimal changes to the segfault code that i can understand pls.

The pointer is not malloc 'ed, you are dereferencing an invalid pointer because your array is an array of poitners, and it's elements are not pointing to valid memory.

Try this

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

struct data
{
    int val;
};

int main(void)
{
    struct data *var[2];
    /* You need to malloc before dereferencing `var[0]` */
    var[0] = malloc(sizeof(var[0][0]));
    if (var[0] != NULL)
    {
        var[0]->val = 6;
        printf("%d\n", var[0]->val);

        free(var[0]);
    }
    return 0;
}

also, using (*var)->val = 6 is absolutely unnecessary and confusing.

In the second case, you should also do almost the same thing, except that the array of pointers is a pointer to an array of poitners and hence needs malloc() too, so your second example accidentally works because there is enough memory malloc() ed but it's also wrong, you should do it this way

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

struct data
{
    int val;
};

int main(void)
{
    struct data **var;
    var = malloc(2 * sizeof(var[0]));
    if (var == NULL)
        return -1;
    /* You need to malloc before dereferencing `var[0]` */
    var[0] = malloc(sizeof(var[0][0]));
    if (var[0] != NULL)
    {
        var[0]->val = 6;
        printf("%d\n", var[0]->val);

        free(var[0]);
    }
    free(var);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM