xdevel2000
xdevel2000

Reputation: 21444

Pointer conversions

I read that assigning a pointer to a type to another pointer to another type is illegal; for example, in this book:

C How To Program 7 ed. pag. 299

Common Programming Error 7.7 Assigning a pointer of one type to a pointer of another type if neither is of type void * is a syntax error.

or at this URL:

but hower in the C11 standard is written:

A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned for the referenced type, the behavior is undefined. Otherwise, when converted back again, the result shall compare equal to the original pointer.

So I understand that only if there is an alignment problem the behavior is undefined.

In fact compilers like GCC 4.8 or cl 2013 emits only a warning of assignment from incompatible pointer type.

That exception is not present for void pointer.

So:

int a = 10;
float b = 100.22f;

int *p_a = &a;
float *p_f = &b;

p_a = p_f; // NOT ILLEGAL but WARNING
p_f = p_a; // converted back again. it still works

void *v_p = p_a; // NOT ILLEGAL NO WARNING
p_a = v_p; // converted back again. it still works

Do I understand well? Or Am I missing something?

P.S. Can also anyone show me an example of an "alignment problem"?

Upvotes: 0

Views: 115

Answers (1)

Ingwar
Ingwar

Reputation: 100

You can consider a pointer to be an offset in memory to pointed data, and no matter what type it is. Any standard pointer (not smart ones) has fixed size, depending on system (32 bit or 64). So you can assign them each to other, modern compiler will warn you about dangerous operations, BUT problem is when you try to dereference pointer of incompaitable type. When dereferencing, app looks up the number of bytes corresponding to pointed type, so in next example

int b = 10;
int* pB = &b;
double* pA = pB;

on dereference pB you will get 10 (size of int is 4 bytes), and on dereference pA you will get trash or crash because next 4 bytes (double is 8 bytes) can be memory space allocated for another variable.

Conclusion: keep track of pointer types when assigning them to each others and especially if you assign them indirectly, using void* as intermediary. Legality or illegality of pointer assignment is compiler's matter, the old ones didn't warn you. Assigning to void* is not considered "illegal" maybe because it is generic, unreferencable pointer type (it has undefined referencing size and that restriction is c language restriction), so you can't receive error like in example above.

Upvotes: 2

Related Questions