Skip to the task
Layout
Back to classic view

You are looking at lesson 12. Your place is still lesson 9, task 1: Strings.

RUNTask 6 of 20 · step 3: The first dynamic memoryThe heap in the debugger
The heap in the debugger in practice/12/

A breakpoint at free(squares);, Debug. In Variables press + and type *squares@10.

Checklist

  • Every task is one commit with a clear message.
  • Zero compiler warnings: the code builds with -Werror.
  • Once per topic you step through your code in the debugger (CLion, gdb).
  • Every function has preconditions and postconditions, and assert tests check them.
  • A multi-file program: .h files with Doxygen comments and their own CMake target.
  • Input only through the safe functions of your own input.h.
  • Every error code is checked (fopen, fclose, malloc and so on).
  • CI is clean: no AddressSanitizer or UBSan reports.

Numbered notes in the code explain the important lines.

Details & hint

You should see: squares itself is just an address; *squares@10 shows all 10 squares.

practice 12 memory.c Code Diff +43
A · NEW FILE Create this file. Every line is new: see the green bar.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Returns a new copy of s in dynamic memory, or NULL if there isn't enough.
Before: s != NULL. After: the caller frees the copy with free. */
Note 1: Who frees it is in the contract.
char *copy_string(const char *s) {
size_t size = strlen(s) + 1;
Note 2: +1 – room for the '\0'.
char *copy = malloc(size);
Note 3: A block on the heap: it lives until free.
if (copy == NULL) {
return NULL;
}
memcpy(copy, s, size);
return copy;
}
int main(void) {
size_t n = 10;
int *squares = malloc(n * sizeof *squares);
Note 4: The number of bytes: n times the element size.
if (squares == NULL) {
printf("Out of memory.\n");
return EXIT_FAILURE;
}
for (size_t i = 0; i < n; i++) {
squares[i] = (int)((i + 1) * (i + 1));
}
printf("Squares:");
for (size_t i = 0; i < n; i++) {
printf(" %d", squares[i]);
}
printf("\n");
free(squares);
squares = NULL;
Note 5: After free – NULL: the old address isn't yours.
char *name = copy_string("Ona Petraite");
if (name == NULL) {
printf("Out of memory.\n");
return EXIT_FAILURE;
}
printf("Copy: %s (%zu bytes)\n", name, strlen(name) + 1);
free(name);
return EXIT_SUCCESS;
}
opened for this task
$ .\build\debug\practice\12\p12_memory.exe
Squares: 1 4 9 16 25 36 49 64 81 100
Copy: Ona Petraite (13 bytes)