pointers-memory · beginner · ~15 min

Generic in-place memory swap

Perform generic type-agnostic memory manipulation by treating pointers as raw byte sequences.

Challenge

In dynamically typed languages, swapping variables is trivial. In C, generic swapping across arbitrary data types requires swapping raw memory byte-by-byte through unsigned char* pointers.

Your Task

Implement:

void generic_swap(void *a, void *b, size_t size);

Swap size bytes between memory addresses a and b.

Rules

  1. If a == NULL, b == NULL, a == b, or size == 0, do nothing.
  2. Cast pointers to unsigned char* and swap all size bytes in place.

Example

int x = 10, y = 20;
generic_swap(&x, &y, sizeof(int)); // x is now 20, y is now 10

double d1 = 3.14, d2 = 2.71;
generic_swap(&d1, &d2, sizeof(double)); // d1 is now 2.71, d2 is now 3.14

Input format

a, b: generic memory pointers; size: byte length to swap.

Output format

Modifies memory at a and b in place.

Constraints

C11 freestanding. Swap byte-by-byte.

Starter code

#include <stddef.h>

/* Swap size bytes between memory locations a and b. */
void generic_swap(void *a, void *b, size_t size) {
    (void)a; (void)b; (void)size;
}

Common mistakes

Allocating dynamic memory for temporary buffer; sign-extending signed char during swap.

Edge cases to handle

a == b does nothing; size == 0 does nothing; NULL pointers do nothing.

Background lessons

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.