Friday, November 9, 2007

incrementing void pointer?

Will the following program execute?void main()
{
void *vptr = (void *) malloc(sizeof(void));
vptr++;
}


Output of this program depends on the compiler।
1) If you are using a ANSI C or C++ compiler then you cannot take the sizeof(void) and you cannot increment a void* pointer. So, you will get the follwoing errors.

ANSI C++ forbids taking the sizeof a void type.
ANSI C++ forbids incrementing a pointer of type `void *'

NOTE: Try this with CC compiler under unix

2)If you are using gcc compiler then sizeof(void) will return 1.
so one byte will be allocated and when u try to increment the void* pointer it will be incremented by one byte.

NOTE: output as seen in gdb;
(gdb) p sizeof(void)
$1 = 1
(gdb) p vptr
$5 = (void *) 0x13030
(gdb) n
4 vptr++;
(gdb) p vptr
$6 = (void *) 0x13031

No comments:

Post a Comment