Writing code for 32-bit vs 64-bit
What you'll learn: How to write code that adapts to different processor architectures by avoiding assumptions about the size of data types.
The Shrinking Suitcase
Imagine you are packing clothes for a trip. In a "32-bit world," your suitcase (the CPU register) is exactly 4 units wide. In a "64-bit world," your suitcase is 8 units wide. The biggest mistake C programmers make is assuming that because a piece of clothing fits perfectly in the 32-bit suitcase, it will behave the same way in the 64-bit one.
In C, the size of a pointer changes based on the architecture. On a 32-bit system, a pointer is usually 4 bytes; on a 64-bit system, it is 8 bytes. However, a standard int often remains 4 bytes on both. If you try to stuff a 64-bit pointer into a 32-bit int, you’ll chop off half the address, causing your program to crash.
Use Portable Type Aliases
To write code that works on both systems, stop guessing how many bytes a type uses. Instead, use the headers provided by the C standard, like <stdint.h> and <stddef.h>.
If you need an integer that is guaranteed to be large enough to hold a pointer, use uintptr_t. If you are counting objects in memory or indexing an array, use size_t. These types "morph" to fit the architecture they are compiled on.
#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
int main() {
int secret_value = 42;
int *ptr = &secret_value;
// BAD: Assuming an int can hold a pointer (Fails on 64-bit)
// unsigned int address_bad = (unsigned int)ptr;
// GOOD: uintptr_t scales to the CPU architecture
uintptr_t address_safe = (uintptr_t)ptr;
// GOOD: size_t is the correct type for sizes and offsets
size_t array_size = sizeof(ptr);
printf("Pointer address: %p\n", (void*)address_safe);
printf("Size of a pointer on this system: %zu bytes\n", array_size);
return 0;
}
Alignment and Padding
Beyond just the size of types, 64-bit systems often prefer data to be "aligned" differently. A 64-bit CPU likes to grab data in 8-byte chunks. If you define a struct with a mix of small and large types, the compiler might add "padding" (empty space) between variables to keep them aligned. Never assume the size of a struct is simply the sum of its parts; always use sizeof() to let the compiler tell you the truth for that specific architecture.
Key takeaway
Always use size_t for memory sizes and uintptr_t for pointer-to-integer conversions to ensure your code runs safely on both 32-bit and 64-bit systems.