Could someone help explaining why this part of my code isn't working?
typedef struct {
char *something;
} random;
random *rd;
rd->something = calloc(40, sizeof(char)); // This is the line which crashes
strncpy(rd->something, aChar, 40);
The program works if I write it as such:
random rd;
rd.something = calloc(40, sizeof(char));
strncpy(rd.something, aChar, 40);
But I think this is wrong when handling memory, that's why I want help with the first scenario.
There's no memory allocated to the struct pointed by rd.
Try:
typedef struct {
char *something;
} random;
random *rd = malloc (sizeof(random));
rd->something = calloc(40, sizeof(char)); // This is the line which crashes
strncpy(rd->something, aChar, 40);
It is because your defined pointer
random *rd;
is not properly initialized and therefore you get a segmentation fault. The second version works, because you actually allocate rd
. To make the first version work as well, allocate memory for *rd
with
random *rd = (random*)malloc(sizeof(random));
Case 1:
random *rd;
// Create *pointer* to struct of type random . Doesn't point to anything.
rd->something = calloc(40, sizeof(char));
// Use it by trying to acquire something which doesnt exist and it crashes
Case 2:
random rd;
// Create a random struct
rd.something = calloc(40, sizeof(char));
// Use it . Works good
===========================
For Case 1, you need to allocate a struct first , make the pointer point to it and then use the ->
operator to modify the values
It will work, but first allocate memory to rd. rd = (random *) calloc(1,sizeof(random));
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.