Monday, 15 June 2015

Define pointer to memory address and print contents C++ -



Define pointer to memory address and print contents C++ -

i want print out things given memory addresses.

using code, can define variable, define pointer , print contents using pointer.

char buf[100]; void *p = buf; strcpy(p, "test string"); printf("address: %x\n", &buf); printf("contents: %c\n", p);

what want specify memory address, , print out contents of block. tried experimenting incrementing , decremeting p, doesn't print out anything.

an interesting little problem. 1 should occur every programmer sooner or later, either out of curiosity or cussedness.

essentially 4 parts.

express address want integer of appropriate size. cast integer pointer type. dereference pointer value of type. print value. [if desired, increment address , repeat.]

for simplicity i'll utilize address of 0x1000 , integer contents.

int address = 0x1000; int* pcontent = (int*)address; int content = *pcontent; printf ("address %p: content %08x\n", pcontent, content);

two points should made.

this undefined behaviour, inevitable if want result. the address chose valid memory or trigger trap error or anything. you'll have experiment different addresses find out which.

[many years ago used strategy print out entire contents of memory on machine had 96kb of memory, led interesting hacking possibilities. digress.]

c pointers

No comments:

Post a Comment