Search code examples
stringhexstrtoull

strtoul() not working as expected?


I am trying to convert a string such as "0x7ffd01767a60" to hexadecimal so I can compare pointers. Not sure if this is the best decision.

I am doing this:

    char *address = "0x7ffd01767a60";

    strtol(address,NULL,16);
    printf("%lp",address);

And I am getting this: 0x7ffd01764120

EDIT: It seems I was printing the string address ignoring the function return. Thanks Jens! and schlenk.

SOLVED! This is what I do

    char *address = "0x7ffd01767a60";
    void *p;
    unsigned long int address_hex = strtol(address,NULL,16);
    p = (void*) address_hex;

    printf("%p",p);

printf prints the same memory address.


Solution

  • You're printing the address of the string itself while ignoring the result of the strtoul() function call. This should work:

    const char *address = "0x7ffd01767a60";
    
    unsigned long int address_hex = strtoul(address, NULL, 16);
    // Check for errors in errno
    printf("%lx\n", address_hex);
    

    Also, personally I prefer code to be as explicit as possible which is why I passed 16 as the base parameter.

    Note: Please read the documentation on the return value, to make sure that you identify errors correctly.