Search code examples
c++cpointershexmemory-address

Display contents (in hex) of 16 bytes at the specified address


I'm attempting to display the contents of a specific address, given a char* to that address. So far I had attempted doing it using the following implementation

int mem_display(char *arguments) {
    int address = *arguments; 
    int* contents_pointer = (int*)address;
    int contents = *contents_pointer;
    printf("Address %p: contents %16x\n", contents_pointer, contents);              
}

But I keep getting a "Segmentation Fault (Core Dumped)" error. I attempted to make a dummy pointer to test on

char foo = 6;  
char *bar = &foo;

But the error still persists


Solution

  • I'm finding it hard to explain what the problem is because almost every single line in your code is wrong.

    Here's what I would do:

    void mem_display(const void *address) {
        const unsigned char *p = address;
        for (size_t i = 0; i < 16; i++) {
            printf("%02hhx", p[i]);
        }
        putchar('\n');
    }