Jean
Jean

Reputation: 22745

GCC pointer cast warning

I am wondering why GCC is giving me this warning:

test.h: In function TestRegister:
test.h:12577: warning: cast to pointer from integer of different size

Code:

#define Address   0x1234
int TestRegister(unsigned int BaseAddress)
{
    unsigned int RegisterValue = 0;
    RegisterValue              = *((unsigned int *)(BaseAddress + Address)) ;
    if((RegisterValue & 0xffffffff) != (0x0 << 0))
    {
            return(0);
    }
    else
    {
            return(1);
    }
}

Upvotes: 0

Views: 1273

Answers (3)

If you include <stdint.h> and if you compile for the C99 standard using gcc -Wall -std=c99 you could cast to and from intptr_t which is an integer type of the same size as pointers.

RegisterValue = *((unsigned int *)((intptr_t)(BaseAddress + Address))) ;

Upvotes: 1

BRPocock
BRPocock

Reputation: 13924

Among other things, you're assuming that a pointer will fit into an unsigned int, where C gives no such guarantee… there are a number of platforms in use today where this is untrue, apparently including yours.

A pointer to data can be stored in a (void*) or (type*) safely. Pointers can be added to (or subtracted to yield) a size_t or ssize_t. There's no guaranteed relationship between sizeof(int), sizeof(size_t), sizeof(ssize_t), and (void*) or (type*)…

(Also, in this case, there's no real point in initializing the var and overwriting it on the next line…)

Also unrelated, but you realise that != (0x0 << 0)!= 0 and can be omitted, since if (x) = if (x != 0) … ? Perhaps that's because this is cut down from a larger sample, but that entire routine could be presented as

   int TestRegister (unsigned int* BaseAddress)
     { return ( (0xffffffff & *(BaseAddress + Address)) ? 0 : 1 ); }

(Edited: changed to unsigned int* as it seems far more likely he wants to skip through at int-sized offsets?)

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272687

Probably because you're on a 64-bit platform, where pointers are 64-bit but ints are 32-bit.

Rule-of-thumb: Don't try to use integers to store addresses.

Upvotes: 2

Related Questions