Skip to content
KALANBLON
Show contents

Chapter 5 of 7 · 20 min

Structures and dynamic allocation

By the end of this chapter, you'll be able to

  • Define a structure with struct and typedef
  • Access fields with . and, through a pointer, with ->
  • Allocate an array whose size is only known at run time with malloc
  • Check the result of malloc and free the memory with free
  • Recognise a memory leak and a use after free

Structures

A structure is a type you create, made up of several fields:

#include <stdio.h>

typedef struct {
    char name[32];
    double price;
    int stock;
} Product;

void show(const Product *p) {
    printf("%-8s %7.2f  (stock: %d)\n", p->name, p->price, p->stock);
}

void apply_discount(Product *p, double percent) {
    p->price = p->price * (1 - percent / 100);
}

int main(void) {
    Product coffee = {"Coffee", 8.50, 12};
    Product tea = {"Tea", 4.00, 30};

    coffee.stock -= 2;                // direct access with .
    apply_discount(&tea, 25);         // we pass the address
    show(&coffee);
    show(&tea);
    return 0;
}
Coffee      8.50  (stock: 10)
Tea         3.00  (stock: 30)
  • typedef struct { … } Product; defines a new type called Product. You then declare variables of this type just like an int.
  • coffee.stock accesses the field stock of the variable coffee.
  • Through a pointer to a structure, you write p->stock, a shortcut for (*p).stock.
  • We usually pass the address of a structure to functions: it avoids copying all its fields, and the function can change it. With const, it promises not to.
  • In the format, %-8s left-aligns the text over 8 characters and %7.2f reserves 7 characters for the number. Like strlen, printf counts bytes: names with accents (é takes 2 bytes) would therefore look a little shorter on screen.

Dynamic allocation

Until now, the size of every array was written in the code. With malloc ("memory allocation"), from <stdlib.h>, you ask for memory while the program runs, of whatever size you want. malloc returns the address of the reserved area, or NULL if there's no more memory available.

This memory doesn't disappear at the end of the function: it stays reserved until you give it back with free. You're responsible for it.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int n = 0;
    if (scanf("%d", &n) != 1 || n <= 0) {
        return 1;
    }
    double *readings = malloc(n * sizeof *readings);
    if (readings == NULL) {
        printf("Not enough memory\n");
        return 1;
    }
    for (int i = 0; i < n; i++) {
        readings[i] = (i + 1) * 1.5;
    }
    printf("Last reading: %.1f\n", readings[n - 1]);
    free(readings);
    readings = NULL;
    return 0;
}
4
Last reading: 6.0

n * sizeof *readings computes the number of bytes: n times the size of a double. Writing sizeof *readings rather than sizeof(double) stays correct even if you change the pointer's type one day. Once allocated, the pointer is used exactly like an array.

Using p after free means accessing memory that no longer belongs to you.

Step 6 of 6
Text description of the animation
  1. malloc reserves the requested memory and returns the address of its start.
  2. If memory runs out, malloc returns NULL. Always check before using p.
  3. The area is used like an array, without ever going past box n - 1.
  4. free gives the memory back to the system. Setting p to NULL avoids reusing it by mistake.
  5. Without free, the area stays reserved until the program ends: that's a memory leak.
  6. Using p after free means accessing memory that no longer belongs to you.

Your turn

Worked exercise

Worked exercise: the value of the stock

Using the Product structure from this chapter, write a function double stock_value(const Product products[], int n) that returns the sum of price * stock. Allocate with malloc an array of 3 products (rice at 2.5 with 40 in stock, oil at 6 with 10, sugar at 1.2 with 50), display the total value, then free the memory.

Hint 1
You can't assign a char array with = after its declaration. The simplest is to assign a whole structure: products[0] = (Product){"Rice", 2.5, 40};.
Hint 2
In the loop, products[i].price accesses the field of the i-th product.
Show the solution and common mistakes
#include <stdio.h>
#include <stdlib.h>

typedef struct {
    char name[32];
    double price;
    int stock;
} Product;

double stock_value(const Product products[], int n) {
    double total = 0;
    for (int i = 0; i < n; i++) {
        total += products[i].price * products[i].stock;
    }
    return total;
}

int main(void) {
    int n = 3;
    Product *products = malloc(n * sizeof *products);
    if (products == NULL) {
        return 1;
    }
    products[0] = (Product){"Rice", 2.5, 40};
    products[1] = (Product){"Oil", 6.0, 10};
    products[2] = (Product){"Sugar", 1.2, 50};
    printf("Stock value: %.2f\n", stock_value(products, n));
    free(products);
    return 0;
}
Stock value: 220.00

Common mistakes:

  • Writing products[0].name = "Rice";: an array can't be assigned. Use whole-structure assignment, or snprintf(products[0].name, sizeof products[0].name, "Rice");.
  • Allocating malloc(n): that reserves n bytes, not n products. What follows writes outside the area.
  • Forgetting free(products);: AddressSanitizer reports a leak at the end of the program.

Summary

  1. 1typedef struct { … } Name; creates a type that groups several fields.
  2. 2You access a field with . on a variable, and with -> through a pointer.
  3. 3malloc(n * sizeof *p) reserves memory at run time; always check it doesn't return NULL.
  4. 4Every malloc has exactly one free; then set the pointer to NULL.
  5. 5Memory leaks and use after free: AddressSanitizer detects them.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.