Lukas' Notes

memory c

Definition

Memory Pointer

A pointer is a C data type that stores a memory address and is tagged with the type of the object at that address. The type tag is what makes pointer arithmetic scale: adding 1 to an int* moves the address by sizeof(int) bytes, so the pointer lands on the next integer, not the next byte. A pointer lets a program access or modify a variable that is not in scope by passing a reference to it rather than a copy of its value.

Operators

The two core pointer operators

  • &x — the address-of operator: yields a pointer to x (e.g. int *p_a = &a; takes the address of a).
  • *p — the dereference operator: yields the value stored at the address p points to (e.g. int y = *p_a; reads the integer at p_a), and *p = v writes v through the pointer.

Pointer Arithmetic

Arithmetic scaled by the pointed-to type

Arithmetic on a pointer depends on its type — equivalently, on the size of the object it addresses.

  • increment (p++): step to the address of the next object of that type;
  • add/subtract an integer (p + k): the address of the object at distance k;
  • subtract another pointer of the same type (p - q): the count of objects that fit between the two addresses.

For a char* the step is 1 byte; for an int* on a 64-bit platform it is typically 4 bytes; for a long* it is 8 bytes. The type, not the raw byte count, is what the programmer manipulates.

Structs and the Arrow Operator

Reaching a struct field through a pointer

Passing a large struct by value to a function would copy it in full. Instead the function takes a pointer to the struct and reads only the fields it needs, which is why void update_font(struct Book *book, int size) { book->fontsize = size; } is idiomatic. The -> operator is syntactic sugar for (*book).title — dereference the pointer and immediately access the named member.

Why Pointers Exist

The three jobs pointers do

  • pass by reference — let a function read or modify a caller’s variable without copying the whole object (the +-performance motivation);
  • byte-indexed access — give fine-grained, direct control over memory, which is exactly the power that makes C unsafe;
  • dynamic memory — point at objects allocated at runtime on the heap (see the memory cluster).

The cost

Nothing in the language stops a pointer from being incremented past the end of its object, freed twice, or used after its target has been deallocated — these are all memory-safety hazards and the root cause of the bugs the cluster studies.