Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
}
like image 490
Rodion Avatar asked Dec 21 '22 08:12

Rodion


2 Answers

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.

like image 54
md5 Avatar answered Dec 24 '22 02:12

md5


"The strdup() function shall return a pointer to a new string, which is a duplicate of the string pointed to by s1." source

So it's quite understandable that the pointers differ.

like image 40
Michael Avatar answered Dec 24 '22 01:12

Michael