Search code examples
cposixc89

Valid to de-reference an integer-as-pointer literal in C


Is it portable/valid C to dereference an integer literal treated as an address? ie, if I want to set a 64-bit value at memory address 0x12345678 to 123, is the following portable and valid C, at least by C89 standards:

*(uint64_t *)(0x12345678) = 123ULL;

I see no compiler warnings (tested via gcc -std=c89 -Wall input.c), but I recall seeing a question on this topic some time back where a case was made for storing the address in an intermediate variable rather than directly de-referencing an integer literal (which has been cast to a pointer address).


Solution

  • As long as the address 0x12345678 is valid and has an uint64_t object, there's no problem with the cast or directly using an integer. But it may not be valid address in all platforms. So, if you know what you are dealing with, it's fine.

    Fixed width types were introduced only in C99. So, I find it paradoxical when you are asking about portability of cast to uint64_t* in C89 :)