Javed
Javed

Reputation: 795

Should the compiler warn on pointer arithmetic with a void pointer?

I was compiling C program using gcc 4.7.2. I have sum a address which is void * type with some offset. (void* + size) should give warning. If it is not then how many bytes it will be added to if size is 1 & if size is 50. my only concern at should give warning that we are adding something to void pointer ?

 12         int size = 50;
 /*Allocate a block of memory*/
 14         void *BlockAddress   = malloc(200);
 15         if(!BlockAddress)
 16                  return -1;
 17         address1             = (int *)BlockAddress;
 18         address2             = BlockAddress + 1*size;
 19         address3             = BlockAddress + 2*size;

Thanks

Upvotes: 6

Views: 10877

Answers (3)

glglgl
glglgl

Reputation: 91119

Pointer arithmetic with void * is a GCC extension and not standard C.

Better don't do things like these. Either use a char * BlockAddress = malloc(200); or cast it for address2 and address3 as well.

Upvotes: 10

Sadique
Sadique

Reputation: 22831

You are not supposed to do pointer arithmetic on void pointers.

From the C Standard

6.5.6-2: For addition, either both operands shall have arithmetic type, or one operand shall be a pointer to an object type and the other shall have integer type.

6.2.5-19: The void type comprises an empty set of values; it is an incomplete type that cannot be completed.

GNU C allows the above by considering the size of void is 1.

From 6.23 Arithmetic on void- and Function-Pointers:

In GNU C, addition and subtraction operations are supported on pointers to void and on pointers to functions. This is done by treating the size of a void or of a function as 1.

So going by the above lines we get:

 address2             = BlockAddress + 1*size; //increase by 50 Bytes
 address3             = BlockAddress + 2*size; //increase by 100 Bytes

Upvotes: 12

It'sPete
It'sPete

Reputation: 5211

This is perfectly valid. The void* contains an address and adding one is just pointing to the next byte in memory. Nothing to worry about here...

Upvotes: 0

Related Questions