Skip to the task
Layout
Back to classic view

You are looking ahead. Your place is still task 1: malloc.

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 git diff: every line is new (+43).
--- /dev/null
+++ b/practice/12/memory.c
@@ -0,0 +1,43 @@
+ #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. */
+ char *copy_string(const char *s) {
+ size_t size = strlen(s) + 1;
+ char *copy = malloc(size);
+ if (copy == NULL) {
+ return NULL;
+ }
+ memcpy(copy, s, size);
+ return copy;
+ }
+
+ int main(void) {
+ size_t n = 10;
+ int *squares = malloc(n * sizeof *squares);
+ 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;
+
+ 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)