Peter Roman
Peter Roman

Reputation: 117

Memory Allocation in Dynamic Linked List of Structs

What's the difference in allocating memory with Malloc or Calloc in this example?
With Calloc the memory breaks, but with Malloc is fine!
My example is similar to (but with many values):

enter image description here

If the code is wrong, how should I do it?

typedef struct {
    int ID, age;
} person;

typedef struct {
    person *person;
    struct NO *next;
} NO;

...   // with calloc, the memory breaks
      // with  (NO*)malloc(sizeof(NO))  it´s fine

NO *p1, *px1, *px2;

px2 = (NO*)calloc(1, sizeof(NO));
p1 = px2;
px2->person->ID = 1; px2->person->age = 30;
px2->next = NULL;
px1 = px2;

px2 = (NO*)calloc(1, sizeof(NO));
px2->person->ID = 2; px2->person->age = 20;
px2->next = NULL;
px1->next = px2;

...

Upvotes: 0

Views: 36

Answers (1)

John Bollinger
John Bollinger

Reputation: 180093

What's the difference in allocating memory with Malloc or Calloc in this example?

Provided that a and b are both positive and a * b does not overflow, the difference between calloc(a, b) and malloc(a * b) is only that calloc initializes the allocated memory to all-bits-zero. Nothing else.

With Calloc the memory breaks, but with Malloc is fine!

Your program is faulty regardless of whether you use calloc() or malloc(), whether it breaks noisily or not. You allocate memory for a NO, but then you dereference its person pointer without first assigning it to point to a valid object. The result is undefined regardless of which allocation function you use.

Upvotes: 1

Related Questions