Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Cast Integer Value to Pointer Address Without Triggering Warnings

I have the following variable

uint32_t Value = 0x80

0x80 represents an address in the memory e.g.

// Write 2 at address 0x80
*(uint32_t*)((uint32_t)0x80) = 2;

How can i cast Value to a Pointer, so it points to 0x80?

uint32_t *Pointer = ?? Value;

This:

(uint32_t*)(uint32_t)Value;

returns:

warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
like image 734
Progga Avatar asked Jul 20 '17 16:07

Progga


People also ask

Can you cast an int to a pointer?

An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.

Can we assign integer value to pointer variable?

Yes you can. You should only assign the address of a variable or the result of a memory allocation function such as malloc, or NULL.

What happens when you cast int to pointer?

A cast from integer to pointer discards most-significant bits if the pointer representation is smaller than the integer type, extends according to the signedness of the integer type if the pointer representation is larger than the integer type, otherwise the bits are unchanged.

Can we store integer in pointer?

Yes, you can.


1 Answers

To handle integer to object pointer conversion, use the optional integer uintptr_t or intptr_t types. Function pointers are a separate matter.

The following type designates an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to pointer to void, and the result will compare equal to the original pointer C11dr 7.20.1.4 1

uintptr_t

Then convert the void * to the desired type.

#include <stdint.h>
uintptr_t Value = 0x80;
uint32_t *Pointer = (void *) Value;

If 0x80 was not derived from a valid uint32_t *, the result in undefined behavior (UB). Yet it sounds like OP is on a platform with memory mapped data locations.

like image 81
chux - Reinstate Monica Avatar answered Nov 11 '22 22:11

chux - Reinstate Monica