Dries Jans
Dries Jans

Reputation: 107

Best datatype for a memdump of a specific address

I'm writing a memdump application in C and the goal is to print a real piece of the application memory of a specific address. The code I already have is this:

void memdump(byte_t *ptr, long size ) {

...

  typedef unsigned char byte_t;
  byte_t data[size];
  //&data[0] = &ptr;
  byte_t * pointer_to_byte = data;


  for (size_t j = 0; j < size; j+=10) {
    printf("%p ",&data[j]);
    for (size_t i = j; i < j+10; i++) {
      printf("%02x ",*(pointer_to_byte+i));
    }
    for (size_t i = j; i < j+10; i++) {
      if (isprint(*(pointer_to_byte+i))) {
        printf("%c",*(pointer_to_byte+i));
      } else {
        printf("." );
      }
    }
      printf("\n" );
    }
}

main.c:

    void  *start_addr;
...
    scanf("%p", &start_addr);
...
    memdump( (byte_t*)start_addr, size );

You can see that I use an array to obtain the memory block, but this might not be the best way. Now I would like to get the address as a parameter to scan and my question is what is the best datatype to get this address and any idea's how I can change my code up so I can use the specific address? I already use a pointer to print the data and the char, so a pointer is the best way I think.

Upvotes: 0

Views: 85

Answers (2)

ensc
ensc

Reputation: 6994

void const * is the best datatype for ptr; everything else will require casts. size should be of type size_t too:

void memdump(void const *ptr, size_t size ) {
    uint8_t const *data = ptr;

    for (size_t i = 0; i < size; ++i) {
        ...

Upvotes: 0

adrtam
adrtam

Reputation: 7241

How about this:

void memdump(byte_t *ptr, long size ) {
  byte_t * baseptr; /* base addr for each row */
  for (size_t j = 0; j < size; j+=10) { /* row loop */
    baseptr = ptr+j;
    printf("%p ",baseptr);
    for (size_t i = j; i < j+10; i++) { /* hex code */
      printf("%02x ",*(baseptr+i));
    };
    for (size_t i = j; i < j+10; i++) { /* char print */
      if (isprint(*(baseptr+i))) {
        printf("%c",*(baseptr+i));
      } else {
        printf(".");
      };
    };
    printf("\n" );
  };
};

Upvotes: 1

Related Questions