0

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.

Fjodor
  • 529
  • 1
  • 7
  • 19
  • the second approach is the correct one. you can fix the first too, but you probably don't need it. – Karoly Horvath Aug 12 '14 at 13:52
  • 2
    `random *rd;` , `rd` is uninitialize. needs `rd = malloc(sizeof(random));` or `rd = &random_obj;` – BLUEPIXY Aug 12 '14 at 13:53
  • in first approach first you need to allocate memory for rd and then allocate memory for something. Then it'' work fine. In second case you are allocating memory to rd on stack so no need to allocate memory for structure and one allocation for something will be required which you are doing, hence it's working. Hope this answers your question. – instance Aug 12 '14 at 13:53
  • There's nothing wrong with the second one (it's better than the first) as long as you don't need the object to persist beyond its scope. By the way, `sizeof(char)` is 1. – chris Aug 12 '14 at 14:11

4 Answers4

2

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);
miluz
  • 1,353
  • 3
  • 14
  • 22
0

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));
Sebastian
  • 8,046
  • 2
  • 34
  • 58
0

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

Suvarna Pattayil
  • 5,136
  • 5
  • 32
  • 59
0

It will work, but first allocate memory to rd. rd = (random *) calloc(1,sizeof(random));