parxch parxch - 2 years ago 153
C Question

Is incrementing implicidly cast void pointer legal C?

I was wondering if this kind of pointer magic is valid C or whether it is just undefined behavior.

#include <stdlib.h>
#include <stdio.h>
int main(void) {
void *foo = malloc(sizeof(int) + sizeof(double));
int *iptr = foo++;
double *dptr = foo;
printf("iptr = %p\n", iptr);
printf("dptr = %p\n", dptr);

Answer Source

Incrementing a void pointer is not defined by C, and is a compiler extension. If you want to increment the pointer by the size of a type int, cast it to that type beforehand.

Let me point out that allocation done in the snippet is at best implementation-defined behavior. If the resulting pointer assigned to the pointer to double is not correctly aligned1, the behavior is undefined.

1 (Quoted from: ISO/IEC 9899:201x Pointers 7)
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 68) for the referenced type, the behavior is undefined.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download