Search code examples
c++cpointerstype-conversionstrdup

Converting char* to int after using strdup()


Why after using strdup(value) (int)value returns you different output than before? How to get the same output?

My short example went bad, please use the long one: Here the full code for tests:

#include <stdio.h>
#include <iostream>

int main()
{

    //The First Part
    char *c = "ARD-642564";
    char *ca = "ARD-642564";

    std::cout << c << std::endl;
    std::cout << ca << std::endl;

//c and ca are equal
    std::cout << (int)c << std::endl;
    std::cout << (int)ca << std::endl;


    //The Second Part
    c = strdup("ARD-642564");
    ca = strdup("ARD-642564");

    std::cout << c << std::endl;
    std::cout << ca << std::endl;

//c and ca are NOT equal Why?
    std::cout << (int)c << std::endl;
    std::cout << (int)ca << std::endl;

    int x;
    std::cin >> x;
}

Solution

  • Because an array decays to a pointer in your case, you are printing a pointer (ie, on non-exotic computers, a memory address). There is no guarantee that a pointer fits in an int.

    • In the first part of your code, c and ca don't have to be equal. Your compiler performs a sort of memory optimization (see here for a full answer).

    • In the second part, strdup allocates dynamically a string twice, such that the returned pointers are not equal. The compiler does not optimize these calls because he does not seem to control the definition of strdup.

    In both cases, c and ca may not be equal.