LET'S TALK TECHNICAL

This blog is intended to help people prepare for the job interviews and improve their analytical skills. We have posted difficult datastructures and algorithm questions and puzzles. Interview experiences section is for the people to post their interview experiences.Views expressed here are of their personal and the blog author doesn't take any responsibility for the same.

-

Followers

Jobs

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

Popular Posts