Generating hex value depending on size of size_t

254 Views Asked by At

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?

5

There are 5 best solutions below

5
Vlad from Moscow On BEST ANSWER

For the two's complement representation of integers you can use memset declared in header <string.h> in C or std::memset declared in header <cstring> in C++ as for example

size_t value;
memset( &value, 0xaa, sizeof( size_t ) );

Or in the both languages you can write

size_t value = ( size_t )-1 / 3 * 2;
1
selbie 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);
3
gulpr 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

2
Eric Postpischil On

In C: SIZE_MAX/3*2.

In C++: std::numeric_limits<size_t>::max()/3*2.

0
chux - Reinstate Monica 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.