Reputation: 536
I want to print out things from given memory addresses.
Using this code, I can define a variable, define a pointer to it and print its contents using the pointer.
char buf[100];
void *p = buf;
strcpy(p, "Test string");
printf("Address: %X\n", &buf);
printf("Contents: %c\n", p);
What I want to do is to specify a certain memory address, and print out the contents of that block. I tried experimenting by incrementing and decremeting p, but it doesn't print out anything.
Upvotes: 1
Views: 5887
Reputation: 10868
An interesting little problem. One that should occur to every programmer sooner or later, either out of curiosity or cussedness.
Essentially four parts.
For simplicity I'll use an address of 0x1000 and integer contents.
int address = 0x1000;
int* pcontent = (int*)address;
int content = *pcontent;
printf ("Address %p: content %08x\n", pcontent, content);
Two points should be made.
[Many years ago I used this strategy to print out the entire contents of memory on a machine that had just 96KB of memory, which led to some interesting hacking possibilities. But I digress.]
Upvotes: 5
Reputation: 310980
You have to define pointer p as
char *p = buf;
or to use casting then incrementing p. For example
p = ( char *)p + n;
For example
printf( "%s\n", ( char *)p + 5 );
You may not increment/decrement pointers of type void *
because void
in incomplete type.
Also the format specifiers in these calls
printf("Address: %X\n", &buf);
printf("Contents: %c\n", p);
are wrong.
If you want to print out a string you have to specify %s
. if you wnat to print only one character then you should write
char *p = buf;
printf("Contents: %c\n", p[0]);
or
void *p = buf;
printf("Contents: %c\n", ( ( char *)p )[0]);
Upvotes: 1
Reputation: 955
You could try something like this:
void printMemory(void* mem, int bytes){
char* p = (char*) mem;
for(int i=0;i<bytes;i++){
printf("%x ",p[i] & 0xff);
if(i%8 == 7)
printf("\n");
}
}
This will print 8 bytes per row.
Upvotes: 0
Reputation: 106012
You are using wrong specifier to print the address. Use %p
and cast argument to void *
.
printf("Address: %p\n", (void*)buf);
and to print string
printf("Contents: %s\n", p);
Upvotes: 3
Reputation: 81926
If we wanted to print random bytes from around memory, we would want to use:
char *p = buf;
printf("Address: %p\n", p);
printf("Contents: 0x%02x\n", *p);
Let's note though, that given a random address, dereferencing it can cause the application to fail. You can not assume that all of the memory space is valid.
Upvotes: 0
Reputation: 584
You are using %c instead use %s to print string printf("Contents: %s\n", p);
Upvotes: 0