BETA Try the new lesson view
Code

The first dynamic memory

First – the same kind of memory, just from the heap: an array through malloc and a copy of a string returned by a function.

Create practice/12:

add_executable(p12_memory memory.c)

memory.c:

  • char *copy_string(const char *s) – malloc(strlen(s) + 1): one byte more, for the '\0' at the end. Its contract says the caller frees the copy.
  • main: malloc(n * sizeof *squares) and the NULL check, 10 squares, free and squares = NULL.
  • Then copy_string("Ona Petraite"), its size in bytes and free(name).

Run it

p12_memory and ▶ (this program reads no files, so the folder doesn't matter):

Squares: 1 4 9 16 25 36 49 64 81 100
Copy: Ona Petraite (13 bytes)

12 characters, plus the '\0': 13.

The heap in the debugger

A breakpoint at free(squares);, Debug. In the Variables window squares is just an address and the first element. Press + and type *squares@10 (GDB: 10 elements from this address): all 10 squares show. The pointer itself doesn't know how many elements are behind it – only you do (n).

Commit: Allocate with malloc and free.