Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we assign a value to a given memory location?

Tags:

c

pointers

memory

I want to assign some value (say 2345) to a memory location(say 0X12AED567). Can this be done?

In other words, how can I implement the following function?

void AssignValToPointer(uint32_t pointer, int value)
{

}
like image 469
Gopinath Avatar asked Feb 21 '12 06:02

Gopinath


1 Answers

C99 standard draft

This is likely not possible without implementation defined behavior.

About casts like:

*(uint32_t *)0x12AED567 = 2345;

the C99 N1256 standard draft "6.3.2.3 Pointers" says:

5 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. 56)

GCC implementation

GCC documents its int to pointer implementation at: https://gcc.gnu.org/onlinedocs/gcc-5.4.0/gcc/Arrays-and-pointers-implementation.html#Arrays-and-pointers-implementation

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.

so the cast will work as expected for this implementation. I expect other compilers to do similar things.

mmap

On Linux you can request allocation of a specific virtual memory address](How does x86 paging work?) with the first argument of mmap, man mmap reads:

If addr is NULL, then the kernel chooses the (page-aligned) address at which to create the mapping; this is the most portable method of creating a new mapping. If addr is not NULL, then the kernel takes it as a hint about where to place the mapping; on Linux, the kernel will pick a nearby page boundary (but always above or equal to the value specified by /proc/sys/vm/mmap_min_addr) and attempt to create the mapping there. If another mapping already exists there, the kernel picks a new address that may or may not depend on the hint. The address of the new mapping is returned as the result of the call.

So you could request for an address and assert that you got what you wanted.