I'm trying to generate a value denoting an invalid address. On 32-bit platforms, I want the value 0xaaaaaaaa. On 64-bit platforms, I want 0xaaaaaaaaaaaaaaaa. Is there a way to do this without using preprocessor directives?
Generating hex value depending on size of size_t
254 Views Asked by cleong AtThere are 5 best solutions below
On
As other comments above have said, NULL or nullptr is the only true invalid address.
But if you really need a to compute a 32-bit or 64-bit repeating AA pairs...
Take advantage that all modern machine architectures will do fine with this and truncate to the lower 32-bit.
size_t s = (size_t)(0xAAAAAAAAAAAAAAAAULL);
You might not even need the ULL suffix in the constant. Different compilers give different warnings about 64-bit literals.
This is more portable:
size_t s = (size_t)((0xAAAAAAAAULL << 32) | 0xAAAAAAAA);
On
If you like weird solutions then.
size_t getAAAAs(void)
{
size_t result;
memset(&result, 0xaa, sizeof(result));
return result;
}
int main(void)
{
size_t res = getAAAAs();
printf("%zx\n", res);
}
https://godbolt.org/z/4rjxh1Ge1
It will be optimized out to a simple immediate load. It will cover all possible future sizes of size_t
On
To form an address of AAA..., use uintptr_t, not size_t using a variation of others` answers.
The size of an address is often like size_t, yet may differ and its the optional uintptr_t that usual meets the address-as-an-integer need.
// C solution
#include <stdint.h>
void *aaa = (void *) (UINTPTR_MAX/3*2);
Alternatively, go right to it.
void *aaa;
memcpy(&aaa, 0xAA, sizeof aaa);
Beware that assigning an arbitrary value to an pointer can lead to UB .
The bit pattern of an address and its converted to/from integer may differ, even if the same size.
For the two's complement representation of integers you can use
memsetdeclared in header<string.h>in C orstd::memsetdeclared in header<cstring>in C++ as for exampleOr in the both languages you can write