Understanding integer vs pointer in C: Memory Rules That Matter

Understanding integer vs pointer in C: Memory Rules That Matter Understanding integer vs pointer in C: Memory Rules That Matter

A pointer may print as a hexadecimal number, but that does not make it an ordinary integer with permission to access memory. The distinction between integer vs pointer in C affects alignment, object lifetime, compiler optimization, and whether a program has defined behavior at all. Code that converts an address to uintptr_t, changes the number, and converts it back may work on a familiar machine—until a new compiler, optimization level, allocator, or architecture exposes an assumption the C language never guaranteed.

Consider this seemingly reasonable example:

#include <stdint.h>
#include <stdlib.h>

int main(void) {
    int *p = malloc(2 * sizeof *p);
    if (p == NULL) return 1;

    uintptr_t address = (uintptr_t)p;
    address += sizeof *p;
    int *q = (int *)address;

    *q = 42;
    free(p);
}

On conventional GCC and Clang targets, this will often appear to access p[1]. Nevertheless, ISO C gives a much stronger and clearer guarantee to int *q = p + 1; than to the integer detour. Understanding why requires separating machine addresses from C pointer values.

What is the difference between an integer and a pointer?

An integer is a value in an integer type’s numeric range. Arithmetic on it follows the rules for that type, including modulo arithmetic for unsigned integers. A pointer is a value associated with a type and a location in the C abstract machine. It can point to an object or function, one position past an array, or no object through a null pointer.

A pointer’s representation may contain a virtual address, but C does not require it to be only an address. An implementation may use tags, bounds, capabilities, segment information, authentication data, or metadata tracked outside the visible bits. Even on a flat-address machine, the compiler can reason about the object from which a pointer originated.

This is why printing a pointer with %p and seeing the same digits as an integer does not establish semantic equivalence. The displayed value is an implementation-defined representation intended for diagnostics, not a portable description of everything the pointer means.

What uintptr_t and intptr_t actually guarantee

The types uintptr_t and intptr_t, declared by <stdint.h>, are optional. An implementation provides them only if it has unsigned and signed integer types capable of representing converted void * values as required. Their central purpose is round-tripping:

int value = 7;
void *original = &value;
uintptr_t bits = (uintptr_t)original;
void *restored = (void *)bits;

if (restored == original) {
    /* The round trip compares equal. */
}

Object pointers can also convert to void * and back to their original type while preserving equality. Function pointers are a separate category and are not covered by the object-pointer guarantee.

The guarantee does not say that every integer is a valid address. It also does not say that adding to a converted integer produces the same result as C pointer arithmetic. A fabricated value may be misaligned, outside any live object, reserved by the system, or incapable of being represented as a usable pointer.

Outside specifically guaranteed cases, pointer-to-integer and integer-to-pointer results are implementation-defined. A pointer-to-integer conversion can also fail to be representable in the chosen integer type. The optional uintptr_t avoids that width problem for supported object-pointer round trips; it does not grant universal dereference rights.

Pointer arithmetic carries object boundaries

Defined pointer arithmetic operates within an array object. If p points to an array element, p + n may point to another element or one position past the array, provided the result remains within those limits. The one-past pointer may be compared or subtracted appropriately, but not dereferenced.

int *p = malloc(2 * sizeof *p);
if (p != NULL) {
    int *q = p + 1;  /* Defined derivation within the allocation. */
    *q = 42;
    free(p);
}

Integer arithmetic has no knowledge of those boundaries. Adding sizeof(int) to a numeric address may reproduce the expected hardware address, but the language does not automatically treat the result as a pointer derived through the array. Nor does integer arithmetic check alignment. Converting an odd address to int *, for example, may produce an incorrectly aligned pointer; dereferencing it can cause undefined behavior in C or a hardware fault.

Pointer provenance: where did this pointer come from?

Pointer provenance is the term commonly used for information connecting a pointer to its originating storage instance. It helps describe cases that raw address arithmetic cannot: two allocations can reuse the same numeric address at different times, yet they are different objects with different lifetimes.

Suppose a program saves the integer representation of a malloc pointer, frees the allocation, and later receives a new allocation at the same visible address. The old number does not portably become authority to access the new object. Lifetime rules, the implementation-defined integer conversion, and the compiler’s provenance model all matter.

The current C standard, ISO/IEC 9899:2024—commonly called C23—defines conversion, lifetime, pointer arithmetic, and effective-type rules, but provenance remains a technically subtle area of standards and compiler work. It is safer to rely on explicit standard guarantees than to infer a universal rule from one compiler experiment. John Regehr’s influential What Is a Pointer? discussion illustrates why apparently simple address reconstruction can challenge both programmers and compiler designers.

Why GCC and Clang may optimize integer-derived pointers differently

At -O0, GCC and Clang generally translate operations directly and retain little high-level analysis. A pointer reconstructed through integer arithmetic may therefore appear to work exactly like a normally derived pointer. That observation is not proof of defined behavior.

At -O2 or -O3, optimizers use alias analysis, object lifetimes, allocation properties, alignment, and undefined-behavior assumptions. Modern GCC and Clang usually recognize straightforward, unchanged pointer-to-uintptr_t-to-pointer round trips on conventional platforms. They may even generate identical machine code for p + 1 and the opening integer-arithmetic example. More complicated arithmetic, masking, lifetime changes, or control flow can prevent that recognition.

GCC pointer behavior and Clang pointer behavior are not required to match in cases outside ISO C’s guarantees. Their optimizers use different internal representations and analyses, and those analyses evolve. One compiler release may conservatively assume that an integer-derived pointer aliases an object, while another may prove that a transformation is valid under its interpretation of the program.

A useful test procedure is:

gcc -std=c23 -Wall -Wextra -O0 test.c
GCC -std=c23 -Wall -Wextra -O3 test.c
clang -std=c23 -Wall -Wextra -O0 test.c
clang -std=c23 -Wall -Wextra -O3 test.c

Also test with AddressSanitizer and UndefinedBehaviorSanitizer where supported. Compare generated assembly and results across targets, but interpret them correctly: successful execution demonstrates compiler behavior for that build, not an ISO C guarantee. Sanitizers also cannot detect every provenance or strict-aliasing violation.

Same numeric address does not mean interchangeable pointer

Pointer equality and integer equality answer different questions. Pointers to live objects can be compared with == and != under C’s pointer comparison rules. Ordering comparisons are generally meaningful only for pointers into the same array object. Converting unrelated pointers to uintptr_t and comparing the numbers can be useful for platform-specific diagnostics, but it does not create a portable ordering of C objects.

Object identity also matters to optimization. If two pointers display the same address but arose from different storage lifetimes or unsupported integer fabrication, the compiler is not necessarily required to treat them as interchangeable. A hardware address is only one part of the analysis.

Provenance does not replace strict aliasing

A correctly derived pointer can still be used incorrectly. Under strict aliasing and effective-type rules, stored objects normally must be accessed through a compatible type, with specific exceptions such as character types used to inspect object representation.

float f = 1.0f;
uintptr_t u = (uintptr_t)&f;
int *ip = (int *)u;
int n = *ip;  /* Not a portable way to inspect float bits. */

Passing through an integer does not erase the object’s effective type. Use memcpy when copying representations between incompatible types. Similarly, malloc provides suitably aligned raw storage, but the way the storage is written and accessed determines its effective type.

Practical rules for low-level C code

  • Prefer pointer arithmetic: Use p + n when navigating an array or allocated region. It expresses bounds and element size directly.
  • Use uintptr_t for a defined purpose: Logging, hashing, ABI fields, tagged-pointer schemes, and hardware interfaces may require integers, but each needs documented platform assumptions.
  • Do not dereference fabricated addresses casually: In embedded systems and kernels, integer addresses may represent memory-mapped registers, but validity comes from the implementation, linker map, architecture, and volatile-access rules—not portable ISO C.
  • Preserve alignment and range: Masks and offsets must not produce addresses outside the intended region or alignment required by the pointed-to type.
  • Respect lifetime: Numeric address reuse does not revive a pointer to a freed allocation or expired automatic object.
  • Audit security-sensitive conversions: Truncation, wraparound, attacker-controlled offsets, and validation performed before arithmetic can lead to out-of-bounds access.

Operating-system code, memory allocators, debuggers, and firmware sometimes must operate below portable C’s abstraction. Such projects should isolate conversions, use implementation-defined compiler facilities where necessary, document the supported architectures, and test every optimization configuration. The SEI CERT C INT36-C guidance provides additional rules and examples for avoiding unsafe pointer-integer conversions.

Frequently asked questions

Is a pointer just an integer containing a memory address?

No. It may have an address-like representation, but a C pointer also participates in type, lifetime, alignment, object-boundary, and implementation rules. Some architectures use pointer representations that cannot be reduced to an ordinary flat address.

Is converting a pointer to uintptr_t always safe?

It is safe for the supported round-trip purpose when uintptr_t exists and the original object pointer remains valid. Arithmetic on the integer, narrowing it, retaining it beyond the object’s lifetime, or dereferencing an arbitrary converted result requires additional guarantees.

Can I add bytes to uintptr_t and convert it back?

You can perform the integer arithmetic, but portable C does not generally guarantee that the resulting pointer is equivalent to one produced by valid pointer arithmetic. Prefer a character pointer for byte-wise movement within an object, then convert back only when alignment, bounds, and type rules are satisfied.

Why does questionable code work at -O0 but fail at -O3?

Unoptimized builds preserve source-level operations more literally. Optimized builds exploit aliasing, lifetime, and undefined-behavior rules. If a program exceeds the standard’s guarantees, changed behavior at higher optimization is often the visible symptom rather than a compiler defect.

Should allocators and embedded software avoid integer addresses entirely?

Not necessarily. They often have legitimate low-level requirements. The key is to treat conversions as platform-specific operations, use documented compiler and architecture guarantees, keep the code localized, and avoid presenting implementation behavior as portable C.

The safest mental model

Treat an integer as a number and a pointer as a language-level reference to storage. uintptr_t provides a valuable transport format when available, but it is not a license to manufacture pointers. Normal pointer arithmetic preserves the clearest relationship to an object and gives compilers, reviewers, and analysis tools the best chance to understand the program correctly.

Leave a Reply

Your email address will not be published. Required fields are marked *