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)
{
}
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)
{
}
The answer depends on some factors. Is your program running within a modern operating system?
If yes, trying to access a memory area that is not mapped will cause a
SIGSEGV
. To accomplish that, you have to use a system specific function to map the region of memory that contains this exact address before trying to access it.Just treat the memory location as a pointer
Note: This will only work if that memory location is accessible and writable by your program. Writing to an arbitrary memory location like this is inherently dangerous.
With the proviso that it's not portable or safe (at all):
C99 standard draft
This is likely not possible without implementation defined behavior.
About casts like:
the C99 N1256 standard draft "6.3.2.3 Pointers" says:
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
so the cast will work as expected for this implementation. I expect other compilers to do similar things.
As far as C is concerned, that's undefined behaviour. My following suggestion is also undefined behaviour, but avoids all the type-based and aliasing-based problems: Use chars.
Alternatively, you can access bytes
q[i]
directly. (This is the part that is UB: the pointerq
was not obtained as the address-of an actual object or as the result of an allocation function. Sometimes this is OK; for instance if you're writing a free-standing program that runs in real mode and accesses the graphics hardware, you can write to the graphics memory directly at a well-known, hard-coded address.)The fact that you are asking this question kind of indicates that you're in over your head. But here you go: