UP | HOME

Code Generation: Pointers and Arrays
Lecture 11

Table of Contents

Pointers

  • Pointers hold memory addresses
  • Memory addresses are also integer values
  • But addresses are differently from regular numbers

SimpleC constructs

Get a reference

Get the memory address of a variable

int x;
pointer<int> y;
x = 10;
y = &x;

What is the value of y?

Dereference a pointer

Get the contents of the memory at a pointer address

int x;
pointer<int> y;
x = 10;
y = &x;
return *y;

What is the value of *y?

Update the contents of a memory via pointer

Get the contents of the memory at a pointer address

int x;
pointer<int> y;
x = 10;
y = &x;
*y = 11;
return x;

What is the value of *y?

What is the value of y?

What is the value of x being returned?

Memory indirect addressing

  • Recall that mov %rax, %rbx moves contents of rax to rbx

Move from memory address of a pointer

  • mov (%rax), %rbx (note parentheses) moves contents of memory at address contained in rax to rbx
  • Handles x = *y

Move to a memory address of a pointer

  • mov %rax, (%rbx) (note parentheses) moves contents of rax to memory address contained in rbx
  • Handles *y = 10

Pointer demo in SimpleC

  • (Demo with gdb)

Pointer arithmetic

  • Pointers are memory address
  • Addresses look no diferent from integers to the machine
  • Assembly allows arithmetic on integers

Tricky example

What does this program return?

main {
  int x;
  int y;
  pointer<int> z;
  x = 1;
  y = 2;
  z = &x - (pointer<int>)8;
  return *z;
}

Arrays

  • Arrays in C are (basically) pointers
  • Array indexing is syntactic sugar for pointer arithmetic

    a[2] is the same as (a + 2 * 8), where 8 is the bitwidth of the array's type

  • Compiler allocates space for arrays on stack
  • Heap-allocated arrays with malloc
  • Implementation in SimpleC is a bonus exercise

Author: Paul Gazzillo

Created: 2020-11-13 Fri 15:17