Search code examples
cpointersmemoryargv

assign a memory address given by argv to a pointer in c


I have a function in C which gets a pointer and prints its disassembly code.

void print_dis(void *addr) {
    print_dis(addr);
}

everything is working just fine but now I would like to pass this memory address from the command line as argv.

How can I pass a memory address and assign it to a pointer so it will run like:

my_prog 0x1234567890abcd

and that print_dis will get this address as addr


Solution

  • You can convert string from argv[1] to unsigned long and assign it to a generic pointer using cast operator (void*), as is shown in example bellow.Be careful, it is dangerous!

    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char* argv[])
    {
       void* ptr = (void*) strtoul(argv[1]+2,0,16);
    
       printf("%lX", (unsigned long) ptr);
    
    }.
    /*
    Output:
    /a.out 0x123456789abcdef
    Result ptr:123456789ABCDEF
    */