cast from pointer to integer of different size – cast to pointer from integer of different size

On a 32-bit system my code compiled without any problem. On a 64-bit system I get the warnings:

warning: cast from pointer to integer of different size
warning: cast to pointer from integer of different size

It turned out the problem was how I was passing an integer to a new thread using pthread_create(). The final argument is a void pointer which can be used to pass a pointer to some data. In my case I was casting an integer to a void pointer in the parent thread, and then re-casting it back to an integer inside the thread.

On a 32-bit system both void pointers and integers occupy 32 bits so everything was ok. On my 64-bit system, integers are still 32-bits but void pointers are 64-bits.

One solution use long instead of int, which are, according to the C99 standard, the same size as void pointers on 32-bit and 64-bit systems.

The proper solution is not to cast integers to pointers in the first place but use pointers throughout:

    void hello(void *i)
    {
        int *pointer;
        
        /* Cast the void pointer to a integer pointer */
        pointer = (int *) i;
        
        /* Display the value pointed to by the pointer */
        printf("Value is: %d\n", *pointer);
    }

    int main()
    {
        int value, *pointer;
        
        /* Assign a value */
        value = 11;
        
        /* Display the original value */
        printf("Value is: %d\n", value);
        
        /* Set the pointer to the location of the value */
        pointer = &value;
        
        /* Call a function, cast the pointer to a void pointer */
        hello((void *)pointer);
        
        return 1;
    }

Of course it should be taken into account that when using threads there is the problem that the value referenced by the pointer could be changed by any of the threads.

This entry was posted in C and tagged , , , , , , . Bookmark the permalink.

2 Responses to cast from pointer to integer of different size – cast to pointer from integer of different size

  1. cleancode says:

    There is no memory allocated to the pointer ‘pointer’ this code will crash unless you do

    pointer = &value

  2. Nick says:

    Thanks – you are right – I’ve updated the post. I was indeed meaning for it to point to the value on the stack, hence no malloc() and free().

Leave a Reply

Your email address will not be published. Required fields are marked *