tags:

views:

74

answers:

3

Hi,

for debugging reasons, how can one in a C program print some memory address?

For instance, how should I do to print the content of address 0x611268 in form of a 4 byte float ?

I know I could use a debugger, but I mean, to print out in screen.

Thanks

+4  A: 

More correctly, printf("Value = %f\n", *((float*)0x611268));

Of course this assumes the address you've given is in the address space of the process running the printf.

Eli Iser
Printing some random piece of memory as a float will give you a totally meaningless float. The sign, exponent and mantissa won't correspond to the bytes in memory in a readily apparent way. It would be far better to print it as Hex, as shown by @karlphillip
abelenky
I agree, but the OP requested float specifically.
Eli Iser
It also assumes that the address you've given is correctly aligned for access as a `float`.
caf
A: 
#include <stdio.h>

int main(void)
{
  // pointer to int (4bytes) that points to memory address 0x611268
  int* address = (int *)0x611268; 

  printf("Memory address is: 0x%x\n", address);

  // Note that this address should exist on your process' memory or 
  // the line below will cause a Segmentation Fault
  *address = 0xdead; //assign a value to that address

  printf("Content of that address is: 0x%x\n", *address);

  return 0;
}
karlphillip
-1 for using implicit conversion to `int` and %x instead of %p
Jens Gustedt
I'm not sure if that is reason enough to justify a -1, but I understand why you did it.
karlphillip
There *is* no implicit conversion here; arguments that are part of a variable argument list go through the default promotions (which doesn't affect pointer types) and then are passed as-is. You either need to explicitly cast to `(unsigned)`, or use `%p`.
caf
+1  A: 

The correct format specifier to print out contents of pointers is "%p":

fprintf(stderr, "myVar contains %p\n", (void*)myVar);
Jens Gustedt
+1 for casting to `void*`.
pmg