CS 208 w20 lecture 2 outline

1 Review

1.1 POLL: If the word size of a machine is 64‐bits, which of the following is usually true? (pick all that apply)

  • 64 bits is the size of a pointer
  • 64 bits is the size of an integer

1.2 POLL: By looking at the bits stored in memory, I can tell if a particular 4‐bytes is being used to represent an integer, floating point number, or string.

1.3 POLL: If the size of a pointer on a machine is 6 bits, the address space is how many bytes?

2 Pointers

2.1 First look

Memory diagram

  • The number 240 is stored at address 0x20 (240 = 0xf0 = 0x00 00 00 f0 using little endian).
  • A pointer stored at address 0x08 and points to the contents at address 0x20.
  • A pointer to a pointer is stored at address 0x00.
  • The number 12 is stored at address 0x10. Is it a pointer? How do we know values are pointers or not?
  • How do we manage use of memory?

2.2 C example

c-assignment.png

Memory diagram

int* p; // p: 0x04
int x = 5; // x: 0x14, store 5 at 0x14
int y = 2; // y: 0x24, store 2 at 0x24
p = &x; // store 0x14 at 0x04
// load the contents at 0x04 (0x14)
// load the contents at 0x14 (0x5)
// add 1 and store sum at 0x24
y = 1 + *p;
// load the contents at 0x04 (0x14)
// store 0xF0 (240) at 0x14
*p = 240;

2.3 POLL: C mystery

int a = 10;
int b = 20;
int *pa = &a;
a += 5;
int *pb = &b;
*pa = *pb - *pa;
*pb += a;
printf("a = %d b = %d\n", a, b);

3 C Arrays

Memory diagram

int a[6]; // declaration, stored at 0x10

// indexing:
a[0] = 0x015f; 
a[5] = a[0];

// No bounds checking
a[6] = 0xbad; // writes to 0x28
a[-1] = 0xbad; // writes to 0xc

// an "array" is just a pointer to an element 
int* p; // stored at 0x40

// these two lines are equivalent
p = a;
p = &a[0];

// write to a[0]
*p = 0xa;

4 C Strings

Just an array of char (array of 1-byte values) ending with a NULL terminator (0x00 or '\0')

4.1 POLL: how would you declare an array of three strings (i.e., what is the type signature)?

5 C Memory Management, C Structures

mem-layout.png

5.1 point_test.c

6 Why C?

6.1 Why learn C?

  • Think like actual computer (abstraction close to machine level) without dealing with machine code
  • Understand just how much Your Favorite Language provides
  • Still widely used
  • Pitfalls still fuel devastating reliability and security failures today.

6.2 Why not use C?

  • Probably not the right language for your next personal project.
  • It "gets out of the programmer's way" even when the programmer is unwittingly running toward a cliff.
  • Advances in programming language design have produced languages that fix C's problems while keeping its strengths.
    • Rust is a good example