1. Home
  2. Explore
  3. Computer Science
  4. Pointers and Memory

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Pointers and Memory

🧠 Memory, Pointers, and File I/O

This week's content introduces pointers, a fundamental concept in C programming that allows for low-level memory manipulation. While challenging, understanding pointers is crucial for comprehending how computers manage data internally. This knowledge is applied to understanding image representation and file operations.

🖼️ Image Representation and Pixels

Images are composed of pixels, each containing bits or bytes that define its color. When an image is enlarged, the individual pixels become more apparent, revealing their hard vertical and horizontal edges.

🔳 Bitmap Images

The simplest image format, like a bitmap image, is essentially a grid of bits.

  • A 0 might represent black.

  • A 1 might represent white.

For example, a grid of 0s and 1s can form a simple image, like a smiley face.

🎨 Color Representation

For color images, a single bit (0 or 1) is insufficient. Typically, 24 bits (3 bytes) are used per pixel to represent a combination of red, green, and blue (RGB) values. This allows for a much wider range of colors.

🔢 Hexadecimal Notation

To understand how colors and memory addresses are represented, it's helpful to learn hexadecimal (base 16) notation.

  • Binary is base 2 (0, 1).

  • Decimal is base 10 (0-9).

  • Hexadecimal is base 16, using 16 distinct digits.

📊 Hexadecimal Digits

Hexadecimal uses digits 0-9 and then letters A-F to represent values 10-15:

  • 0-9: Represent their usual decimal values.

  • A: Represents 10

  • B: Represents 11

  • C: Represents 12

  • D: Represents 13

  • E: Represents 14

  • F: Represents 15

🌈 Hexadecimal in Color Codes

Hexadecimal is commonly used in web development and image editing (e.g., Photoshop) to specify colors.

  • A hash sign (#) followed by six hexadecimal digits (e.g., #FF0000) is a common format.

  • The six digits are typically broken into three pairs, representing Red, Green, and Blue values.

    • 000000 (no red, no green, no blue) represents black.

    • FFFFFF (maximum red, maximum green, maximum blue) represents white.

    • FF0000 (maximum red, no green, no blue) represents red.

    • 00FF00 (no red, maximum green, no blue) represents green.

    • 0000FF (no red, no green, maximum blue) represents blue.

🧮 Hexadecimal Math

The mathematical system for hexadecimal is the same as binary or decimal, but with powers of 16 for each column.

  • For a two-digit hexadecimal number:

    • The rightmost digit is the 16016^0160 (1's) place.

    • The left digit is the 16116^1161 (16's) place.

Example:

16116^1161 (16s place)

16016^0160 (1s place)

Decimal Value

0

0

0

0

9

9

0

A

10

0

F

15

1

0

16

F

F

(15×16)+(15×1)=240+15=255(15 \times 16) + (15 \times 1) = 240 + 15 = 255(15×16)+(15×1)=240+15=255

  • Two hexadecimal digits can represent values from 00 to FF, which corresponds to 0 to 255 in decimal.

  • A single hex digit can be represented by 4 bits.

  • Two hex digits represent 8 bits, or 1 byte, making hexadecimal a convenient way to visually represent byte values.

📍 Hexadecimal in Memory Addresses

Computer memory addresses are often displayed in hexadecimal notation, prefixed with 0x (e.g., 0x7ffef3c2925c).

  • The 0x is a convention to indicate that the following number is hexadecimal; it has no mathematical meaning.

  • This prefix resolves ambiguity, as 10 could be decimal 10 or hexadecimal 16. With 0x10, it's clearly hexadecimal.

💾 Pointers: Addresses in Memory

A pointer is a variable that stores the memory address of another variable. Understanding pointers is key to low-level memory manipulation in C.

⚙️ Pointer Operators in C

  • & (Address-of Operator): Returns the memory address of a variable.

    • Example: &n gives the address where the variable n is stored.

  • * (Dereference Operator): Accesses the value stored at a memory address (i.e., "goes to" the address).

    • Example: *p accesses the value at the address stored in p.

  • %p (Format Code for printf): Used with printf to display a pointer's value (a memory address) in hexadecimal.

📝 Declaring and Using Pointers

To declare a pointer, you specify the type of data it points to, followed by an asterisk * and the pointer's name.

  • Example: int *p; declares p as a pointer to an integer.

    • This means p will store the address of an integer.

    • int *p = &n; stores the address of n into pointer p.

#include <stdio.h>

int main(void)
{
    int n = 50;
    int *p = &n; // p stores the address of n

    printf("%i\n", n);  // Prints the value of n (50)
    printf("%p\n", p);  // Prints the address stored in p (e.g., 0x123)
    printf("%i\n", *p); // Dereferences p to print the value at its address (50)
}
  • When declaring a pointer for the first time (int *p), the * signifies that p is a pointer.

  • When subsequently using the pointer (*p), the * means to "dereference" it (go to the address it holds).

  • Pointers typically occupy 8 bytes (64 bits) on modern systems to address gigabytes of memory.

🗺️ Pointer Metaphor: Treasure Maps

  • A pointer variable (p) is like a treasure map that stores an address (like 0x123).

  • The dereference operator (*p) is like following the map to "X marks the spot" to find the actual treasure (the value, e.g., 50).

  • A pointer itself also has an address in memory.

📜 Strings in C: Not a Native Type

A "string" is a high-level concept in C, but it's not a primitive data type like int or char.

  • In C, a string is fundamentally an array of characters terminated by a null character (\0).

  • A string variable actually stores the address of its first character.

💡 typedef for string

The string keyword used in CS50 (e.g., string s = "HI!";) is a convenience provided by cs50.h.

  • It's defined using typedef: typedef char *string;

  • This simply creates an alias: wherever string is used, the compiler treats it as char *.

  • char * is the "real" C way to refer to a string (a pointer to a character).

🔍 String Memory Layout

When string s = "HI!" is declared:

  • An array of characters {'H', 'I', '!', '\0'} is stored in contiguous memory.

  • The variable s (a char *) stores the address of the first character ('H').

Example:

Address

Value

0x123

'H'

0x124

'I'

0x125

'!'

0x126

'\0'

  • The \0 (null character) signifies the end of the string. Functions like printf("%s", s) iterate through characters starting at s's address until \0 is found.

➕ Pointer Arithmetic

Since addresses are numbers, you can perform arithmetic on pointers.

  • s refers to the address of the first character.

  • s + 1 refers to the address of the second character.

  • s + 2 refers to the address of the third character, and so on.

#include <stdio.h>

int main(void)
{
    char *s = "HI!"; // s stores address of 'H'

    printf("%c\n", *s);       // Dereference s: prints 'H'
    printf("%c\n", *(s + 1)); // Dereference s+1: prints 'I'
    printf("%c\n", *(s + 2)); // Dereference s+2: prints '!'
}
  • Array bracket notation (s[0], s[1]) is syntactic sugar for pointer arithmetic (*s, *(s + 1)).

  • %s with printf expects a char * (an address). printf("%s", s + 1) would print "I!" because it starts printing from the address of 'I'.

↔️ Comparing Strings vs. Integers

Comparing primitive types like int with == works because it compares their actual values.

int i = 50;
int j = 50;
if (i == j) // Compares 50 == 50
    printf("Same\n");
else
    printf("Different\n"); // Output: Same

However, comparing strings with == compares their memory addresses, not their character content.

#include <cs50.h> // For get_string
#include <stdio.h>

int main(void)
{
    string s = get_string("s: "); // E.g., "HI!"
    string t = get_string("t: "); // E.g., "HI!"

    if (s == t) // Compares address of s (e.g., 0x123) == address of t (e.g., 0x456)
        printf("Same\n");
    else
        printf("Different\n"); // Output: Different (even if content is same)
}
  • s and t will point to different memory locations, even if they store the same sequence of characters.

  • To compare string content, use strcmp() from string.h.

    • strcmp(s, t) returns 0 if the strings are identical.

📤 Copying Strings and Memory Allocation

Directly assigning one string pointer to another (e.g., string t = s;) does not create a copy of the string's characters. It only copies the address, making both pointers point to the same memory location.

  • If you then modify the string through one pointer, the change is reflected through the other pointer as well.

🛠️ malloc and free for Dynamic Memory

To create a true copy of a string, you need to:

  1. Allocate new memory for the copy.

  2. Copy the characters from the original string to the new memory.

  • malloc() (Memory Allocation): Reserves a specified number of bytes in memory (on the heap) and returns the address of the first byte.

    • Syntax: void *malloc(size_t size);

    • Example: char *t = malloc(strlen(s) + 1);

      • strlen(s): Gets the length of the string s.

      • + 1: Accounts for the null terminator \0.

      • (char *): Casts the void * returned by malloc to char *.

  • free(): Releases previously allocated memory back to the system.

    • Syntax: void free(void *ptr);

    • Example: free(t);

  • Memory Leaks: Forgetting to free() allocated memory can lead to memory leaks, where a program continuously consumes memory without releasing it, eventually causing crashes.

📋 strcpy for String Copying

The strcpy() function (from string.h) simplifies copying string content.

  • Syntax: char *strcpy(char *dest, const char *src);

  • Example: strcpy(t, s); (copies s into t).

#include <cs50.h>
#include <stdio.h>
#include <string.h>   // For strlen and strcpy
#include <stdlib.h>   // For malloc and free
#include <ctype.h>    // For toupper

int main(void)
{
    char *s = get_string("s: ");

    // Allocate memory for the copy
    char *t = malloc(strlen(s) + 1);
    if (t == NULL) // Check if malloc failed
    {
        return 1;
    }

    strcpy(t, s); // Copy s into t

    if (strlen(t) > 0)
    {
        t[0] = toupper(t[0]); // Capitalize first character of t
    }

    printf("s: %s\n", s); // s remains unchanged
    printf("t: %s\n", t); // t is capitalized

    free(t); // Free the allocated memory
}

⚠️ Handling malloc Failures

  • malloc can return NULL if memory allocation fails (e.g., system is out of memory).

  • Always check if the pointer returned by malloc is NULL before using it.

  • NULL (with two Ls) is a special value (address 0) that signifies an invalid memory address.

🗄️ Computer Memory Organization (The Stack and The Heap)

Computer memory is typically organized into distinct regions:

  • Code Segment: Stores the program's machine code (read-only).

  • Global Data Segment: Stores global variables (defined outside any function).

  • Heap: Used for dynamic memory allocation (e.g., malloc). The heap "grows downwards" as more memory is requested.

  • Stack: Used for function calls and local variables. The stack "grows upwards" as functions are called.

📊 Stack Frames and Scope

  • When main is called, a stack frame is created for it, containing its local variables (e.g., x, y).

  • When a function (e.g., swap) is called from main, a new stack frame is pushed onto the stack for swap, containing its local variables (e.g., a, b, tmp).

  • This means variables in main and swap are distinct.

🔄 Passing by Value vs. Passing by Reference

  • Pass by Value: When arguments are passed to a function, copies of their values are made. Changes to these copies within the function do not affect the original variables in the caller. (This is why the first swap function failed to change x and y in main.)

  • Pass by Reference (or Pass by Address): Instead of passing the variable's value, you pass its memory address (a pointer). The function can then use the dereference operator (*) to access and modify the original variable at that address.

#include <stdio.h>

// Correct swap function: takes pointers to integers
void swap(int *a, int *b)
{
    int temp = *a; // Store value at address 'a' in temp
    *a = *b;       // Store value at address 'b' into address 'a'
    *b = temp;     // Store temp's value into address 'b'
}

int main(void)
{
    int x = 1;
    int y = 2;

    printf("x is %i, y is %i\n", x, y);
    swap(&x, &y); // Pass addresses of x and y
    printf("x is %i, y is %i\n", x, y); // Output: x is 2, y is 1
}

💥 Buffer Overflows and Security

  • Heap Overflow: Occurs when malloc allocates too much memory, potentially encroaching on other memory regions.

  • Stack Overflow: Occurs when too many functions are called (e.g., deep recursion), causing the stack to grow beyond its allocated space.

  • Buffer Overflow: A general term for writing data beyond the boundaries of an allocated memory buffer (e.g., an array).

    • This can lead to crashes, undefined behavior, or security vulnerabilities (e.g., overwriting critical program data or injecting malicious code).

    • The CrowdStrike fiasco was an example of a buffer overflow where software tried to access the 21st element of an array of size 20, leading to widespread system crashes.

  • Languages like C offer little protection against buffer overflows, requiring careful programming. Higher-level languages like Python and Java often have built-in defenses.

📂 File Input/Output (I/O)

C provides functions to interact with files, enabling programs to read from and write to persistent storage. This requires using pointers to FILE objects.

📚 File I/O Functions (from stdio.h)

  • FILE *fopen(const char *filename, const char *mode);: Opens a file.

    • filename: Path to the file.

    • mode: Specifies how the file is opened:

      • "r": Read mode (file must exist).

      • "w": Write mode (creates new file or truncates existing file).

      • "a": Append mode (adds to end of existing file or creates new file).

      • "rb", "wb", "ab": Binary modes for raw byte operations.

    • Returns a FILE * pointer to the opened file or NULL if an error occurs.

  • int fclose(FILE *stream);: Closes an opened file.

  • int fprintf(FILE *stream, const char *format, ...);: Prints formatted output to a file.

  • size_t fread(void *ptr, size_t size, size_t count, FILE *stream);: Reads count items, each size bytes, from stream into ptr.

  • size_t fwrite(const void *ptr, size_t size, size_t count, FILE *stream);: Writes count items, each size bytes, from ptr to stream.

📖 Implementing a Phonebook with File I/O

#include <cs50.h> // For get_string
#include <stdio.h> // For FILE, fopen, fclose, fprintf
#include <string.h> // For string functions (not directly used here but often useful)

int main(void)
{
    // Open file in append mode
    FILE *file = fopen("phonebook.csv", "a");
    if (file == NULL) // Error checking
    {
        return 1;
    }

    char *name = get_string("Name: ");
    char *number = get_string("Number: ");

    // Write name and number to file, separated by comma, followed by newline
    fprintf(file, "%s,%s\n", name, number);

    fclose(file); // Close the file
}

📝 Implementing a File Copy Utility (cp)

#include <stdio.h>  // For FILE, fopen, fclose, fread, fwrite
#include <stdint.h> // For uint8_t

// Define a byte type (unsigned 8-bit integer)
typedef uint8_t BYTE;

int main(int argc, char *argv[])
{
    // Check command-line arguments
    if (argc != 3)
    {
        fprintf(stderr, "Usage: cp SOURCE DESTINATION\n");
        return 1;
    }

    // Open source file in binary read mode
    FILE *src = fopen(argv[1], "rb");
    if (src == NULL)
    {
        fprintf(stderr, "Could not open %s for reading.\n", argv[1]);
        return 1;
    }

    // Open destination file in binary write mode
    FILE *dst = fopen(argv[2], "wb");
    if (dst == NULL)
    {
        fprintf(stderr, "Could not open %s for writing.\n", argv[2]);
        fclose(src); // Close source file before exiting
        return 1;
    }

    // Read and write byte by byte
    BYTE buffer; // Declare a buffer to hold one byte
    while (fread(&buffer, sizeof(BYTE), 1, src) == 1) // Read 1 byte from src into buffer
    {
        fwrite(&buffer, sizeof(BYTE), 1, dst); // Write 1 byte from buffer to dst
    }

    // Close files
    fclose(src);
    fclose(dst);
    return 0;
}
  • File I/O functions maintain an internal "cursor" that advances as bytes are read or written, similar to a cassette tape.

  • This allows fread and fwrite to automatically process the next bytes in sequence without explicit pointer arithmetic.

🖼️ Image Manipulation with Pointers (Problem Set 4)

Problem Set 4 often involves manipulating bitmap (BMP) image files using knowledge of file I/O and pointers.

  • BMP files have a specific structure, including headers and pixel data.

  • Pixels are typically stored as a grid, from bottom-left to top-right.

  • Tasks include implementing image filters:

    • Grayscale: Convert an image to black and white by averaging RGB values.

    • Sepia: Apply a sepia tone for an old-fashioned look.

    • Reflect: Flip the image horizontally.

    • Blur: Make the image fuzzy by averaging surrounding pixel values.

    • Edge Detection: (Optional, advanced) Identify object outlines using algorithms that analyze pixel differences.

This week's material, while challenging, provides the foundation for understanding how computers manage data at a fundamental level and how to interact with files directly.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent