The heap - malloc, calloc and free

Asking for memory at run time, what it contains when you get it, and the checks that keep heap code from crashing.

What you'll learn
  • Allocate single structs and arrays of structs on the heap
  • Explain the difference between malloc and calloc, byte by byte
  • Read a struct's layout - field offsets, padding and alignment
  • Check allocations and bound user input

Two programs build Person records on the heap. The first allocates one with malloc and an array of two with calloc:

typedef struct {
    int id;
    char name[50];
    int age;
} Person;

Person *p1 = (Person*) malloc(sizeof(Person));
p1->id = 1;
strcpy(p1->name, "John");
p1->age = 25;

Person *p2 = (Person*) calloc(2, sizeof(Person));
p2[0].id = 2;   // p2[i] is the same as *(p2 + i)

The file’s own comment states the difference correctly: malloc returns uninitialised memory, calloc returns zeroed memory. Here is what that means for the 60 bytes of a Person:

The 60 bytes of a Person, coloured by field. Choose malloc or calloc, then watch the program write id, name and age. Bytes it never writes keep their old content — garbage under malloc, zero under calloc.

Layout: offsets and padding

id sits at offset 0, name at 4, and age at 56 — not 54. An int must start at an address divisible by 4, so the compiler inserts two padding bytes after name, and sizeof(Person) is 60. Checked with offsetof and sizeof on GCC 13 for x86-64. Ordering fields from largest to smallest alignment is the usual way to keep padding down; here it would not help, because 50 + 4 + 4 is not a multiple of 4 either way.

strcpy(p1->name, "John") writes five bytes (with the terminator). The other 45 bytes of name stay as they were. After malloc that is garbage, which is harmless as long as everything reads name as a string — and a leak of old heap contents if the struct is ever written to a file or a network socket. That is one reason to prefer calloc for structs.

Three fixes the compiler points to

Compiled with gcc -Wall, the first program warns:

warning: implicit declaration of function 'strcpy'

strcpy is declared in <string.h>, which the program never includes. GCC 13 guesses a declaration and carries on; GCC 14 and later treat implicit function declarations as an error, so the program no longer compiles. The fix is one line: #include <string.h>.

The second program, 4_practice_struct_calloc_function.c, is more careful — create_human checks for NULL — but two gaps remain:

scanf("%s", ptr->name);        // no limit: a 60-letter name overflows name[50]
struct human* h1 = create_human();
greet(h1);                     // h1 may be NULL here

Use scanf("%49s", ptr->name) to leave room for the terminator, check that scanf returned 1, and check h1 before using it. Finally, the (Person*) cast in front of malloc is needed in C++ but not in C, where it can hide a missing #include <stdlib.h>.

Try it yourself. Print offsetof(Person, age) (from <stddef.h>) and sizeof(Person). Reorder the struct as { char name[50]; int id; int age; } and predict both numbers before printing them. Then run the second program under valgrind and delete one of the delete_human calls: find the leak in the report.

View source on GitHub →