Overview

In this reading, you will learn about the organization of structs in memory. While structs are more complicated than arrays, they share some similarities in terms of memory organization. You’ll also be introduced to the concept of data alignment, whose importance will become more obvious when we begin discussion of caches.

This reading also contains a brief introduction to pointer arithmetic, which is an alternative to using array notation.

Required Reading

Sections 3.9.1 and 3.9.3 (pp. 265-269, 273-275) from the course textbook.

Learning Objectives

BASIC Learning Objectives

Each student will be responsible for learning and demonstrating proficiency in the following objectives PRIOR to the class meeting. The reading quiz will test these objectives.

  1. Given the definition of a struct and (optionally) a set of alignment restrictions, give the offsets of each field in the struct.
  2. Translate a C statement that assigns a value to a field of a struct into the equivalent x86-64 instruction, given the starting address of the struct (e.g. %rdx) and the location of the value you are copying into the field (e.g. %rax).
  3. Given a primitive data type, state the alignment rule for that type.
  4. Convert between a C expression that uses an arrow (->) operator and one that does not.

ADVANCED Learning Objectives

The following objectives should be mastered by each student DURING and FOLLOWING the class session through active work and practice.

  1. Trace and write x86-64 assembly code that includes allocating space for structs and accessing them.
  2. Trace and write C code that uses the “->” operator to access fields of a struct to which you have a pointer.

Pre-class Exercises

These exercises are geared towards mastering the BASIC learning objectives listed above. You are expected to submit them before class and it is highly recommended that you complete them before attempting the reading quiz.

  1. Consider the following struct definition.

    struct TaylorSwift {
        char *p;
        int x;
        char c;
        int y;
    };

    For each of the fields, give its offset from the beginning of the struct assuming the recommended Intel x86-64 data alignments.

  2. Assume that we have an array of TaylorSwift structs. Will there need to be any “padding” at the end of each element in the array, again assuming the recommended Intel alignments?

  3. Consider the following C code.

    struct TaylorSwift ts;
    ts.y = 1989;

    Translate the assignment statement into an equivalent x86-64 instruction, assuming that the starting address of ts is stored in %rbx.

  4. Consider the following C code:

    struct TaylorSwift *tsp = malloc(sizeof(struct TaylorSwift));
    (*tsp).x = 7;

    Convert the statement in the second line to an equivalent statement that uses the arrow (->) operator.