pointers-memory · intermediate · ~15 min

Generic Byte-Sized Memory Swap

Perform generic memory swapping and array manipulation using void pointers.

Challenge

C standard library algorithms like qsort operate on generic void * pointers. Implementing a generic in-place memory swap requires byte-by-byte exchange between memory locations.

Your Task

Implement:

int generic_swap(void *a, void *b, size_t size);
int generic_reverse(void *base, size_t count, size_t elem_size);

Rules

  1. In generic_swap:
    • If a == NULL, b == NULL, or size == 0, return -1.
    • If a == b, return 0 immediately.
    • Exchange the contents of memory blocks a and b byte-by-byte for size bytes.
    • Return 0.
  2. In generic_reverse:
    • If base == NULL, count == 0, or elem_size == 0, return -1.
    • Reverse the array of count elements in-place using two pointers/indices and generic_swap.
    • Return 0.

Example

int arr[] = {10, 20, 30, 40};
generic_reverse(arr, 4, sizeof(int)); // arr becomes {40, 30, 20, 10}

Input format

a, b, base: void pointers; size, count, elem_size: size_t parameters.

Output format

Returns 0 on successful swap/reverse, or -1 on NULL or zero size.

Constraints

In-place memory manipulation. No dynamic heap allocation.

Starter code

#include <stddef.h>
#include <stdint.h>

int generic_swap(void *a, void *b, size_t size) {
    (void)a; (void)b; (void)size;
    return -1;
}

int generic_reverse(void *base, size_t count, size_t elem_size) {
    (void)base; (void)count; (void)elem_size;
    return -1;
}

Common mistakes

Treating void* as char* without casting; dereferencing void* directly.

Edge cases to handle

Swapping identical pointer returns 0; count == 1 reverse returns 0; odd and even array counts.

Background lessons

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