could anybody explain me how to read DWORD ,WORD ,BYTE in C from specific address in memory?
for example, base address that is returned using MapViewOfFile() function,how can I read a consecutive BYTE,WORD, or DWORD using C ?
Thanks.

- 9,710
- 3
- 34
- 44

- 65
- 1
- 7
-
Do you want the answer for C or C++? – Mats Petersson Apr 30 '13 at 22:58
-
@ Mats Petersson in C please – Vladimir Scofild Apr 30 '13 at 23:01
-
Please realise that there is no BYTE, WORD or DWORD defined in C. They probably are an artifact typedeffed by the windows programming environment. In C, you can just dereference *any* pointer type p by using `*p`. – wildplasser Apr 30 '13 at 23:19
4 Answers
Assuming that the address is aligned suitably for the datatype you are using - this is important as in some architectures, it's invalid to access an "unaligned" address!
In C:
void *address = MapViewOfFile(...);
DWORD *dword_ptr = (DWORD *)address;
WORD *word_ptr = (WORD *)address;
BYTE *byte_ptr = (BYTE *)address;
In C++, the pattern is similar, but instead of a basic C style cast, you should use reinterpret_cast<type*>(address)
, where type
is DWORD
, WORD
, BYTE
, etc. E.g.:
DWORD *dword_ptr = reinterpret_cast<DWORD *>(address);

- 126,704
- 14
- 140
- 227
MapViewOfFile()
returns LPVOID
which is a typedef of void*
. You'll need a cast.
The easiest thing to do would be to read a byte at a time. You don't specify if there's any kind of performance requirement here (nor do you specify your platform, arch, etc), so I'll assume a "byte at a time" is ok.
Note: WORD is defined as short and should be 16-bits in Win32. DWORD is an int and should be 32-bits in Win32.
LPVOID pvAddr= MapViewOfFile(...);
BYTE* pBytes= (BYTE*)pvAddr;
BYTE firstByte= pBytes[0]; /* copy first byte */
WORD w;
memcpy(&w, pBytes+1, 2); /* copy the next two bytes */
DWORD dw;
memcpy(&dw, pBytes+3, 4); /* copy the next 4 bytes */
Hope that helps.

- 87,561
- 32
- 179
- 238

- 380
- 1
- 15
-
better to use markdown code blocks than trying to inject `
` tags directly.
– Evan Teran Apr 30 '13 at 23:05
Well your question has basically two parts:
could anybody explain me how to read
DWORD
,WORD
,BYTE
in C from specific address in memory?That's easy, but probably not what you want, you simply cast the address to a pointer of the desired type.
DWORD x = *((DWORD *)address);
for example, base address that is returned using
MapViewOfFile()
function,how can I read a consecutiveBYTE
,WORD
, orDWORD
using C ?That's also not too bad. You are getting a
void*
fromMapViewOfFile
, simply cast it or assign it to an appropriate pointer type and then you can use it like an array:DWORD *p = MapViewOfFile(...); DWORD x = p[1]; // second DWORD of the mapped file

- 87,561
- 32
- 179
- 238
-
I think you mean second DWORD rather than second byte on that last line? – Caleb Apr 30 '13 at 23:07
MapViewOfFile
returns an LPVOID
(which is equivalent to a void *
) so it can be read like any other pointer.