horro
horro

Reputation: 1309

Displaying a byte content given by an address

I have to display the content of n bytes starting in a specific memory address, i.e: an output for 25 bytes since 0x00004000 (segment text in virtual space) would be #include <stdio.h> #inclu (25 letters)

My idea was to assign to a char *c the address given, like: *c=address; and then printf("%s",c);. For me, conceptually makes sense and I know that in some cases it would cause a segmentation fault if the address is not valid.

However I have implemented it and it always causes a segmentation fault. I use pmap <pid> to know what areas can be displayed (low areas) of that process. When I say "areas that can be displayed" I mean text areas (code).

So, what I am doing wrong? is stupid the assignment *c=address; ?

Upvotes: 1

Views: 126

Answers (2)

Marco
Marco

Reputation: 2897

char *c = address;

for (int i = 0; i < n; i++) {
    putchar(c[i]);
}

Errors in your code

having something like

char *c;
*c = address;

Is invalid, because c is a dangling pointer (you have never initialized it). You want to set the address which c points to to address: c = address

printf("%s",c);

You don't know if c is a proper string, it may contain garbage or may not be n bytes length. That's why I used putchar

Upvotes: 3

Christopher Creutzig
Christopher Creutzig

Reputation: 8774

*c = address puts the value of address into the memory c currently points to. That is what the * is doing. To change where c points, use c = address.

But still, this sounds like a rather, ahem, suboptimal programming exercise.

Upvotes: 1

Related Questions