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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With