Memory Diagramming - kevshouse/exam_quest GitHub Wiki

Memory Diagram for Pointer Drills Visualizing ft_swap Operation

graph TB
    %% Stack Memory Section
    subgraph Stack_Memory[Stack Memory]
        direction TB
        A[a: int] -->|Address 0x1000| A_val[Value: 42]
        B[b: int] -->|Address 0x1004| B_val[Value: 24]
        PTR_X[x: int*] -->|Value: 0x1000| A
        PTR_Y[y: int*] -->|Value: 0x1004| B
        TMP[tmp: int] -->|Value: 42|tmp
    end

    %% Function Steps
    subgraph ft_swap_Steps[ft_swap Operation]
        STEP1["Step 1: tmp = *x"]:::step
        STEP2["Step 2: *x = *y"]:::step
        STEP3["Step 3: *y = tmp"]:::step
    end

    %% Data Flow Connections
    A_val -->|Read by| STEP1
    STEP1 -->|Stores in| TMP
    B_val -->|Read by| STEP2
    STEP2 -->|Writes to| A_val
    TMP -->|Read by| STEP3
    STEP3 -->|Writes to| B_val

    %% Styling
    classDef step fill:#f9f,stroke:#333,stroke-width:2px,color:#000;
    classDef memory fill:#eef,stroke:#ccc;
    classDef changed fill:#ff9,stroke:#f90;
    class A,B,PTR_X,PTR_Y,TMP memory;
    class STEP1,STEP2,STEP3 step;
    class A_val,B_val changed;

Diagram Key

Memory Regions Stack Memory: Shows original variables before ft_swap call

ft_swap Operation: Execution steps inside the function

Data Flow

  1. Solid arrows: Value read operations
  2. Dashed arrows: Value write operations
  3. Color change (yellow): Modified memory locations

Step Execution

Step Action Memory Impact
1 tmp = *x Copies value from a@0x1000 (42) to tmp
2 *x = *y Writes b's value (24) to a's location (0x1000)
3 *y = tmp Writes tmp's value (42) to b's location (0x1004)

Edge Case Diagrams

graph LR
    subgraph Before
        direction TB
        A[a: 42] -->|0x1000| A_val[42]
        B[b: 24] -->|0x1004| B_val[24]
    end

    subgraph After
        direction TB
        A2[a: 24] -->|0x1000| A_val2[24]
        B2[b: 42] -->|0x1004| B_val2[42]
    end

    Before -->|ft_swap| After

Key Takeaways

  • Step 1: Value preservation

    • Original value of a is saved to temporary storage
  • Step 2: First modification

    • b's value overwrites a's original value
  • Step 3: Second modification

    • Saved value from a is written to b's location
  • Net Effect:

    • Values at 0x1000 and 0x1004 are swapped
    • Temporary storage (tmp) is discarded after operation

Debugging Tips

  • Watchpoints: Set in gdb to monitor memory changes:
watch *(int*)0x1000  // Monitor a's location
watch *(int*)0x1004  // Monitor b's location
  • Print interim states:
printf("Step1: tmp=%d, a=%d, b=%d\n", tmp, *x, *y);