tags:

views:

185

answers:

3
+1  Q: 

Memory locations

Can anyone please give a C code to display all the values in a memory location starting from 0 to end?

+2  A: 

You won't be able to do this as dereferencing the zero location will raise a SEGV signal on all Unix systems apart from HP-UX where it depends on either a compiler switch or a run-time attribute whether the zero location can be dereferenced.

Rob Wells
+2  A: 

The question is a bit vague.

You either want to display the entire memory which won't work (at least not easy) due to mapping and swapping.

Or you want to display a piece of allocated memory. Which is easy. You can create a pointer to the memory and display all relevant bytes. Or if you know the layout, you can create a struct. Either way, you need to know where the end is. By knowing the size or a delimiting character.

Gamecat
+5  A: 

Assuming you're on a system without protected memory access, and/or without a MMU so that the addresses used are true physical addresses, this is really simple.

#include <stdio.h>
#include <stdlib.h>

/* Print memory contents from <start>, 16 bytes per line. */    
static void print_memory(const void *start, size_t len)
{
  const unsigned char *ptr = start;
  int count = 0;

  printf("%p: ", ptr);

  for(; len > 0; --len)
  {
    printf("%02X ", *ptr++);
    if(++count >= 16)
    {
      printf("\n%p: ", ptr);
      count = 0;
    }
  }
  if(count > 0)
    putchar('\n');
}

int main(void)
{
  print_memory(NULL, 1024);

  return EXIT_SUCCESS;
}

This should run perfectly fine on e.g. an old Amiga, but is of little use on a modern PC running Linux, Windows, or whatever.

unwind