ECEC 201 · Week 5

Modern Computer: Von Neumann

Memory you ask for with malloc is yours to give back with free.

Week 5 of 10 · Das Frite

ECEC 201 · Week 5 · In class

Memory you ask for with malloc is yours to give back with free.

ECEC 201 · Week 5 · In class

A struct is laid out in memory with padding between members so each one is aligned.

ECEC 201 · Week 5 · Lecture

Every malloc has one free

ECEC 201 · Week 5 · Lecture

Freeing a list without reading freed memory

#include <stdlib.h>

struct node { struct node *next; char *text; };

void list_free(struct node *head)
{
	while (head) {
		struct node *next = head->next;
		free(head->text);
		free(head);
		head = next;
	}
}

ECEC 201 · Week 5 · Lecture

A test that fails loudly

#include <assert.h>
#include "list.h"   /* your own list API */

int main(void)
{
	struct node *list = NULL;

	list = list_insert(list, "a");
	assert(list_find(list, "a") != NULL);
	list = list_remove(list, "a");
	assert(list_find(list, "a") == NULL);
	list_free(list);
	return 0;
}

ECEC 201 · Week 5 · Lecture

Padding: members start on their alignment

struct mixed { char a; int b; char c; };
MemberoffsetofWhy
a0the first member starts at 0
b43 padding bytes, so int starts on a multiple of 4
c8right after b

The size rounds up to the largest member's alignment: 12 bytes here, with a 4-byte int.

ECEC 201 · Week 5 · Lab

Lab

  1. Build a linked list of structs from the lines of a text file, then free it, and write an `assert`-based test that inserts, finds, and removes nodes.
  2. Run the program and the test under valgrind until both report no leaks, and print `sizeof` and `offsetof` for each struct member. Second pass: reorder the members to remove padding, print the new size, and run the test again.

ECEC 201 · Week 5 · Lab

Lab (continued)

  1. Assemble the lab hand-in: The program and its test, the valgrind summary with no leaks, and the member offset table before and after reordering.

ECEC 201 · Week 5 · Lab

Hand in

The program and its test, the valgrind summary with no leaks, and the member offset table before and after reordering.

ECEC 201 · Week 5 · Homework

Homework

ECEC 201 · Week 5 · Homework

Turn in

The hand-computed offset table.

ECEC 201 · Week 5 · Read

Read

On the lab site: the modules do not grade heap use or struct layout. This week does.

ECEC 201 · Week 5 · Next

Week 6

A C file becomes a running program in steps: the preprocessor, the compiler, the assembler, the linker, and the loader.

Arrow keys or space to move, F for full screen, N for speaker notes, Home and End for the first and last slide. Print gives one slide per page.