简体   繁体   中英

In C, how to read the memory chunk preceding an address

Given a struct object or a pointer to one, how can I read, say x bytes of memory, preceding the object? For example, if I know the object start at address 10, how can I read x bytes from address 10-x to address 9? Thank you.

Like Nitzan Shaked said in the comment, cast the pointer to (char *) so that you can do pointer-arithmetic at the byte level. Then do the pointer arithmetic (subtract the number of bytes you need to subtract), then cast it back to a pointer of the type of thing you need to read it as.

Reading bytes from any address is easy: simply cast the pointer to a char* , subtract the desired number of bytes, and start reading, like this:

struct MyStruct {
    int x;
    int y;
} test[100];
...
void *ptr = &test[50];
...
char *start = (char*)prt;
start -= 10;
// You can read from the start pointer now

You need to make sure that the memory that you are trying to read is legal for your application to access. The memory needs to be part of a larger structure that you allocated statically or dynamically. Otherwise, it is undefined behavior, which may lead to a crash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM