CodeBlanks Logo Icon CodeBlanks

Memory management

  • C course
  • Beginner
  • Lesson 115/116
  • 6 min

Add dynamic memory management with malloc and free.

Dynamic Book with malloc

Instead of a fixed array, you can allocate a Book at runtime with malloc. This lets the catalog size be set dynamically.

struct Book *b = malloc(sizeof(struct Book));
strcpy(b->title, "Suç ve Ceza");
b->year = 1866;
free(b);

Here b is a pointer; it points to the Book on the heap. You access members with the -> operator (not dot). When done, you give the memory back with free. This is the basis of dynamic catalogs.

Assigning the title with strcpy

You cannot assign directly to a char array; you copy characters with strcpy. The <string.h> header is required.

strcpy(b->title, "Suç ve Ceza");
b->year = 1866;

Here strcpy copies the second string into the first. year is an int so it can be assigned directly with =. This difference comes from C treating string and integer assignments differently.

Practice Allocate a Book with malloc and print

Add the <stdlib.h> and <string.h> headers. Allocate a Book with malloc(sizeof(struct Book)); set the title to "War and Peace" with strcpy; assign b->year = 1869. Print with print_book(*b); release with free(b).

Starter code

main.c
#include <stdio.h>

struct Book {
    char title[32];
    int year;
};

void print_book(struct Book b) {
    printf("%s %d\n", b.title, b.year);
}

// Allocate a Book with malloc; assign title with strcpy; print with print_book; release with free
int main(void) {
    return 0;
}

Sample solution

main.c
#include <stdlib.h>
#include <string.h>
struct Book *b = malloc(sizeof(struct Book));
strcpy(b->title, "War and Peace");
b->year = 1869;
print_book(*b);
free(b);

Expected output

War and Peace 1869

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Fill in the blank: pointer member access

Question
b____ = 1866;
Answer
b->year = 1866;

Explanation: b->year accesses the pointer's member.

2 Match expression to meaning

Term Meaning
b->title Title member
b->year Year member
malloc Allocates on heap
free Releases heap

3 Which function is called to release a Book allocated with malloc?

  • delete
  • release
  • free Correct answer
  • destroy

Explanation: free gives back heap memory allocated with malloc.

All lessons in Beginner