Page 1 of 1

Dereferencing void pointers

Posted: Mon Dec 01, 2003 12:10 pm
by Therx
I want to use a void* for my syscall interface. I intend to make the syscall interrupt accept the following:-

The function required (number) -> eax
A pointer to the data for the function -> ebx

The trouble is that that I keep getting warnings about dereferencing a void pointer. i'm confused because I didn't get any warning when I defined malloc as a void*.

What is the standards definition of this (I can't find it in my C manual)?

Pete

Re:Dereferencing void pointers

Posted: Mon Dec 01, 2003 1:30 pm
by BI lazy
Are you performing the necessary type casts to convert the void pointers to pointers of correct datatype before dereferencing them?

f. ex. malloc, which returns a void-pointer:

Code: Select all

struct foo *bar; --> a pointer to a  instance of struct foo.

bar=(struct foo *) malloc(sizeof(struct foo)); --> this one stuffs the pointer from malloc into the pointer bar - thus creating an instance of foo in memory ... correctrly casted.

hope this helps

Re:Dereferencing void pointers

Posted: Mon Dec 01, 2003 3:49 pm
by Schol-R-LEA
AFAIK, void pointers cannot be dereferenced unless they are first cast to another pointer type. There are a few reasons for this, starting with the fact that not all pointer types on all systems are interchangeable, and thus using a void* directly is non-portable. More importantly, the compiler does not know the correct size of the object pointed to and thus cannot use pointer arithmetic correctly; in C, [tt]sizeof(void)[/tt] is 1 (or at least that is what I got under Dev-C 4.9.8.5, which is based on gcc 3.2). Nor does it know what operations can be validly performed on it without the type information.

In C, integer to pointer conversions are cast automatically, but most compilers will give a warning on it. Even without a warning, it is best to use a cast any time you use a void pointer.

(EDIT: Additional comments removed afte re-reading you original post.)

HTH. C&CW.