views:

62

answers:

2

I am trying to print the value pointed to by an address but the problem is I need to dereference this pointer based on the size that is passed to me. So something of this sort:

void print(Address addr, Int size) {
...
}

I am a little confused on how to achieve this. Can someone point me in the right direction?

EDIT: Ok so I'm thinking:

char p[80];
memset(p, '\0', 80);
memcpy(p, addr, size);

And then dereference as *p. If there is a better way or a correct way, please let me know

+2  A: 

Your question is very unclear. If you mean you want to dump arbitrary binary data from the address passed, you want something like:

void print(const unsigned char *addr, size_t size)
{
    while (size--) printf("%.2x", *addr++);
}

Or if you mean you want to print character data that's not null-terminated, try:

void print(const char *addr, int size)
{
    printf("%.*s", size, addr);
}
R..
I added the const qualifiers to the `char *` arguments. Since the functions do not (and should not) modify the targets of the pointer arguments, we can let the compiler's optimizer and error-checking know a little more about what's going on inside.
Andy Lester
Thanks for the fix.
R..
A: 

If it is a number, which I assume it is, you will need something like this:

int n=0;
if (size>sizeof(int)) { return; //int is too small };
for (int i=0;i<size;i++) {
  ((char*)(&n))[sizeof(int)-(i+1)] = ((char*)addr)[size-(i+1)];
}
printf("%d",n);
Alexander Rafferty
This code at best has implementation-defined behavior, and more likely undefined behavior...
R..
does it really, why?
Alexander Rafferty
If `size` is less than `sizeof(int)`, part of the representation of `n` remains uninitialized. Also whether you should copy to the beginning or end is implementation-defined (endian dependent).
R..