Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Malloc an array inside a struct

I'm trying to malloc an array inside a struct but I keep getting segmentation errors when I run the program.

The compares function is just something I'm testing so it shouldn't be a part of the problem

typedef struct {
    char *string;
} prod_t;

int
main(int agrc, char **argv){
    int i = 0;
    prod_t *c = NULL;

    char str2[100] = "abcd";
    c->string = (char *) malloc( 5 * sizeof(char));
    strcpy(c->string,str2);

    compares(c->stock,str2,i);

    return 0;
}
like image 841
Kyuu Avatar asked May 18 '15 17:05

Kyuu


2 Answers

The problem is that you're allocating space for the string, but you're not allocating the struct at all. c remains set to NULL and you're trying to dereference it.

Allocate space for the struct before assigning to its members

prod_t *c = malloc(sizeof(prod_t));

And, as a sidenote for your next-to-fix error: this field doesn't exist

c->stock
like image 101
Marco A. Avatar answered Sep 19 '22 05:09

Marco A.


You need to allocate space for the struct before you can assign to the string member:

prod_t *c = malloc(sizeof(prod_t));

Also see Do I cast the result of malloc?

like image 28
Barmar Avatar answered Sep 23 '22 05:09

Barmar