Can you ever assume that pointers to pointers are safe?

I heard from many people that you cannot guarantee that type casting will be lossless. This is only true if you do not know your processor, that is, you have not checked the number of bytes used for your data types? Let me give an example:

If you do the following:

typedef struct
{
    int i;
    char c;
    float f;
    double d;
} structure;

size_t voidPtrSz = sizeof(void *);
size_t charPtrSz = sizeof(char *);
size_t intPtrSz = sizeof(char *);
size_t floatPtrSz = sizeof(float *);
size_t doublePtrSz = sizeof(double *);
size_t structPtrSz = sizeof(structure *);
size_t funcPtrSz = sizeof(int (*)(float, char));

printf("%lu\n", voidPtrSz);
printf("%lu\n", charPtrSz);
printf("%lu\n", intPtrSz);
printf("%lu\n", floatPtrSz);
printf("%lu\n", doublePtrSz);
printf("%lu\n", structPtrSz);
printf("%lu\n", funcPtrSz);

... and the conclusion is as follows:

4
4
4
4
4
4
4

Is it possible to assume that in all cases you can safely resort to pointing a certain data type to another data type pointer? For example, if you do this:

int foo(float, char)
{
}

void *bar(void)
{
    return (void *)foo;
}

int (*pFunc)(float, char) = bar();

Can you safely assume that it pFunchas an address foo?

+4
3

, ?

char* void*. char* void* . undefined, .

, . void* undefined.

, , , ?

. C , undefined, . , , , UB , , , .

+2

, 6.3.2.3 C99:

void . void ; .

, . :

; . , , undefined.

, undefined.

, :

. , undefined. .

.. ( , , char * .)

+6

@Oli Charlesworth .

, , , :

- . . , , , .

, gcc x86, int * p, , p, , p (int *) , 4 ( ) .

A void * - " ". - , , , , void *, , , void .

The pointer to the function contains the address of the function, and the type of the pointer indicates how to call this function (which parameters and which type) and what the function returns.

+1
source

All Articles