problem with "void" 
Author Message
 problem with "void"

Greetings:

The following two problems about the "void" type has been bugging me for a
long time:

1. What is the "void" type and how many bytes does variables declared with
this type occupy in memory?

2. Is it really possible to cast "void" type pointers to anything (int,
char, float, etc.), in other words, is the following code snippet possible?:

{
  void *foo=malloc(sizeof(int));
  foo = (int *) foo;
  printf ("%d", foo);

Quote:
}

 (When I tried to do this in Unix using the GNU C compiler it stops and
flagged me with the message "void not ignored like it's supposed to").

Thanks

Shuo Xiang



Mon, 16 Aug 2004 01:06:59 GMT  
 problem with "void"

Quote:

> 1. What is the "void" type and how many bytes does variables declared with
> this type occupy in memory?

6.2.5#19 says:

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

You cannot declare objects of type void, so there is no sense in
which it takes up space in memory.  You also cannot use the
sizeof operator on a `void' type (because it is incomplete).

Quote:
> 2. Is it really possible to cast "void" type pointers to anything (int,
> char, float, etc.), in other words, is the following code snippet possible?:

It is possible to cast a `void *' to any pointer type for which
they are properly aligned.

Quote:
> {
>   void *foo=malloc(sizeof(int));
>   foo = (int *) foo;

This is fine, because malloc() returns a block of memory that is
properly aligned for any type.  It is, however, pointless, and I
hope you understand that.

Quote:
>   printf ("%d", foo);

This is not allowed.  %d takes an `int' argument.  Use `%p'.

Incidentally, %p requires a `void *' argument; you cannot use any
other pointer type, except possibly a character pointer, and we
had a long debate over that.

Quote:
> }

>  (When I tried to do this in Unix using the GNU C compiler it stops and
> flagged me with the message "void not ignored like it's supposed to").

Show us the entire source code.  I don't see any improper use of
`void' above.
--
int main(void){char p[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.\
 \n",*q="kl BIcNBFr.NKEzjwCIxNJC";int i=sizeof p/2;char *strchr();int putchar(\
);while(*q){i+=strchr(p,*q++)-p;if(i>=(int)sizeof p)i-=sizeof p-1;putchar(p[i]\
);}return 0;}


Mon, 16 Aug 2004 01:42:43 GMT  
 problem with "void"

Quote:

> Greetings:

> The following two problems about the "void" type has been bugging me for a
> long time:

> 1. What is the "void" type

The void type doesn't exist. (It's used only in function prototypes to
indicate that the function doesn't take any arguments/doesn't return
anything).
The void * on the other hand is a generic pointer that can point to any
object in memory. (Note that a function is not an object so don't try to
use a void * to point to a function).

Quote:
> and how many bytes does variables declared with
> this type occupy in memory?

It occupies sizeof(void *) bytes. How many that is depends on the
implementation. You can see how much it is on your system by doing a
printf("%lu\n",(unsigned long) sizeof(void *)); or if you have a c99
compliant compiler printf("%z\n",sizeof(void *));. But it shouldn't matter
in your code how much this actually is.

Quote:
> 2. Is it really possible to cast "void" type pointers to anything (int,
> char, float, etc.), in other words, is the following code snippet
> possible?:

> {
>   void *foo=malloc(sizeof(int));
>   foo = (int *) foo;
>   printf ("%d", foo);
> }

The foo=(int *) foo; is legal but doesn't make much sense. foo is a void *
and casting it to int * is legal and you get an int *. Assigning this int *
to foo again will convert it back to a void * (standard promotion) and the
whole line is a no-op.
The printf is wrong: you tell it that an int is coming as the next
argument, but give it a void *.
Maybe you want to try this:

{
  void *foo=malloc(sizeof(int));
  /* malloc can fail you need to make sure foo!=NULL here */
  *((int *)foo) = 5; /* store 5 in the allocated memory */
  printf ("%d", *((int *) foo));

Quote:
}

This can be done without any casts by using an int * instead of a void *:

{
  int *foo=malloc(sizeof(*foo));
  /* malloc can fail you need to make sure foo!=NULL here */
  *foo = 5; /* store 5 in the allocated memory */
  printf ("%d", *foo));

Quote:
}

Tobias.

Tobias.



Mon, 16 Aug 2004 01:49:03 GMT  
 problem with "void"

Quote:
> Greetings:
> The following two problems about the "void" type has been bugging me for a
> long time:
> 1. What is the "void" type and how many bytes does variables declared with
> this type occupy in memory?

There IS no "void type". What you are seeing below at the malloc call
is the void * type, which is an entirely different thing.
How many bytes a variable declared as void * occupies in memory is
completely system-depdent.

Quote:
> 2. Is it really possible to cast "void" type pointers to anything (int,
> char, float, etc.), in other words, is the following code snippet possible?:

They are not "void" type pointers, they are pointers to void, which is
a somewhat confusing term. It is possible to cast the pointers, but if
they are not properly aligned, you may cause undefined behaviour.
What "properly aligned" exactly means is system-dependent.

Quote:
> {
>   void *foo=malloc(sizeof(int));
>   foo = (int *) foo;

This line is fine, as a pointer returned by malloc() is guaranteed to
be aligned suitably for an int *, and you can assign an int * to a
void *, but it does not buy you anything. You might as well have said:
foo = foo;

Quote:
>   printf ("%d", foo);

This, however, generates undefined behaviour. To print out the value of
pointers, use %p instead of %d.

Quote:
> }
>  (When I tried to do this in Unix using the GNU C compiler it stops and
> flagged me with the message "void not ignored like it's supposed to").

Where exactly does it generate this message? From which line? I don't
see where such a message should come from.

--

| Kingpriest of "The Flying Lemon Tree" G++ FR FW+ M- #108 D+ ADA N+++|
| http://www.helsinki.fi/~palaste       W++ B OP+                     |
\----------------------------------------- Finland rules! ------------/
"A bicycle cannot stand up by itself because it's two-tyred."
   - Sky Text



Mon, 16 Aug 2004 01:55:06 GMT  
 problem with "void"

Quote:

>  1. What is the "void" type and how many bytes does variables declared with
>  this type occupy in memory?

It is an incomplete type, meaning that no objects of this type can
exist. The question about its size is therefore meaningless.

Quote:
>  2. Is it really possible to cast "void" type pointers to anything (int,
>  char, float, etc.), in other words, is the following code snippet possible?:

The types void and void * ("pointer to void") are completely different,
and you seem to confuse them.

You can cast any expression to type void, e.g.:
    (void) 42;
    (void) puts("Hello, World!");
This simply discards the expression's value. It does not really *do*
anything useful and is normally only used for self-documenting code, to
tell a human or a program reading the code that you really meant to
throw the value away.

You can, furthermore, convert freely, without casts, between void * and
any pointer to object type, e.g.:
    int *p = malloc(sizeof *p); /* converts from void * to int * */
    free(p); /* converts from int * to void * */

What was your real question?

Quote:
>  {
>    void *foo=malloc(sizeof(int));

This is OK.

Quote:
>    foo = (int *) foo;

This is legal but pointless; foo will just get its own value back.

Quote:
>    printf ("%d", foo);

This invokes undefined behavior: foo is not an int. You can print
pointers to void with the "%p" format.

Quote:
>  }

>   (When I tried to do this in Unix using the GNU C compiler it stops and
>  flagged me with the message "void not ignored like it's supposed to").

I doubt that it emitted that warning for this code.

Gergo
--
"The Amiga is the only personal computer where you can run a multitasking
operating system and get realtime performance, out of the box."
    -- Peter da Silva



Mon, 16 Aug 2004 02:03:45 GMT  
 problem with "void"

Quote:


> > 1. What is the "void" type

> The void type doesn't exist. (It's used only in function prototypes to
> indicate that the function doesn't take any arguments/doesn't return
> anything).

I'm not sure it's really a type in that case, although it's not a
special-case production in the grammar.

Another use: expressions can be cast to void types.  This is
sometimes seen done to the return value of a function to
explicitly indicate that its result is being thrown away.

--
"What is appropriate for the master is not appropriate for the novice.
 You must understand the Tao before transcending structure."
--The Tao of Programming



Mon, 16 Aug 2004 02:01:26 GMT  
 problem with "void"

Quote:

>  [...] or if you have a c99
>  compliant compiler printf("%z\n",sizeof(void *));. [...]

'z' is a length modifier, not a conversion specifier. That is, it cannot
be used alone: it only says that the following conversion applies to a
size_t (or its signed counterpart, whatever that may be).
To print a size_t in decimal notation, you need to use "%zu".

Gergo
--
no brainer:
        A decision which, viewed through the retrospectoscope,
        is "obvious" to those who failed to make it originally.



Mon, 16 Aug 2004 02:24:54 GMT  
 problem with "void"

Quote:

> Greetings:

> The following two problems about the "void" type has been bugging me for a
> long time:

> 1. What is the "void" type and how many bytes does variables declared with
> this type occupy in memory?

void means nothing - variables should not be of type void,  it is more
a place holder to specify no return or no input parameters.
[??? I think it can be used like a label - not sure about this though,
and I believe it would be bad practice anyway ???]

void* has completely the opposite meaning,  meaning a pointer to
anything (pointer to undefined type) - similar to Java's Object.
Implementation is dependent on the computer type ie. the 680x0 would
probably use 4 bytes for a void* where the UltraSparc would use 8 bytes.
<rant> in my opinion any* would be a better name,  but the ANSI commity
seems to like reducing keywords to the absolute minimum even at the
expense to clarity </rant>

Quote:
> 2. Is it really possible to cast "void" type pointers to anything (int,
> char, float, etc.), in other words, is the following code snippet
> possible?

Yes and No.  I think you are saying and meaning two different
things .. void type pointers (void*) may be copied to any _pointer_
_without_ needing a cast.  However pointers and variables are
completely different eitities. Therefore if you had "void*foo" and
"int*bar" then "bar=foo" is valid and does not require the cast
"bar=(int*)foo".
A cast is more of a type override,  telling the compiler to ignore
the type of the variable and substitute a new type,  therefore you
could cast a pointer to an integer using "anInt = (int) aPointer"
to avoid the warning 'pointer to int without a cast' (this could be
useful for printing out the addresses of variables in memory).

C 2002/2/27



Mon, 16 Aug 2004 07:41:13 GMT  
 problem with "void"

Quote:

> void means nothing - variables should not be of type void,  it is more
> a place holder to specify no return or no input parameters.
> [??? I think it can be used like a label - not sure about this though,
> and I believe it would be bad practice anyway ???]

What do you mean by "used as a label"?


Mon, 16 Aug 2004 03:01:22 GMT  
 problem with "void"

Quote:


>> void means nothing - variables should not be of type void,  it is more
>> a place holder to specify no return or no input parameters.
>> [??? I think it can be used like a label - not sure about this though,
>> and I believe it would be bad practice anyway ???]

> What do you mean by "used as a label"?

Sorry phrased that very badly (thats what comes with writing
messages with one hand and installing Solaris with the other).

I ment to say that labels are essentially of type void,  though
using them as a pointer would be bad practice (union would
normally be better for data in most instances,  and for self
modifying code - best to be avoided even in assembler).
I checked up with the standard and I believe it states that
declairing a variable as type void is not allowed.

C 2002/2/27



Mon, 16 Aug 2004 11:38:03 GMT  
 problem with "void"

Quote:



> >> void means nothing - variables should not be of type void,  it is more
> >> a place holder to specify no return or no input parameters.
> >> [??? I think it can be used like a label - not sure about this though,
> >> and I believe it would be bad practice anyway ???]

> > What do you mean by "used as a label"?

> I ment to say that labels are essentially of type void,

A label marks a statement either as a target for a `goto'
statement or as a case or default label for a `switch'
statement.  A label is not data in any sense.  So WTF are you
talking about?

Quote:
> though using them as a pointer would be bad practice

A label cannot be used as a pointer.  Again, WTF are you talking
about?

Quote:
> (union would normally be better for data in most instances, and
> for self modifying code - best to be avoided even in
> assembler).

???????

Quote:
> I checked up with the standard and I believe it states that
> declairing a variable as type void is not allowed.

This is undeniably true.
--
"The lusers I know are so clueless, that if they were dipped in clue
 musk and dropped in the middle of pack of horny clues, on clue prom
 night during clue happy hour, they still couldn't get a clue."
--Michael Girdwood, in the monastery


Mon, 16 Aug 2004 07:17:39 GMT  
 problem with "void"

Quote:

> Greetings:

> The following two problems about the "void" type has been bugging me for a
> long time:

> 1. What is the "void" type and how many bytes does variables declared with
> this type occupy in memory?

Nothing exists of void type.  No variables are declared of this type,
and these non-existent variables consume no memory.

Quote:

> 2. Is it really possible to cast "void" type pointers to anything (int,
> char, float, etc.),

You can probably convince your compiler with coercive casts to do this.
The behavior is not defined, however.  Pointers should be assigned to
pointers, not ints, chars, floats, etc.

Quote:
> in other words, is the following code snippet possible?:

> {
>   void *foo=malloc(sizeof(int));
>   foo = (int *) foo;
>   printf ("%d", foo);

I think you mean
   printf("%p", (void *)foo);

foo is never an int, and is never properly printed with "%d".

--
Carius est nobis flagellari p doctrina quam nescire.
[leofre ys us beon beswungen for lare thaenne hit ne cunnan.]
 - MS Cotton Tiberius A, xv, fol. 60v (British Library)



Mon, 16 Aug 2004 07:38:27 GMT  
 problem with "void"


Quote:


>> > 1. What is the "void" type

>> The void type doesn't exist.

It certainly exists as a type, although it is not an object type so
you cannot define objects with void type.

Quote:
>> (It's used only in function prototypes to
>> indicate that the function doesn't take any arguments

That is somewhat special syntax and you can view the void keyword as
a placeholder rather than a type if you wish. Still, it occurs where you
wouldnormally see a type in a prototype.

Quote:
>>/doesn't return anything).

The return type of a function is a type even if the function doesn't
return anything. As you mention below void can also be used in casts
and the last time I looked a cast is syntactically a type enclosed
in parentheses. The standard certainly defines void as a type. And of
course void * is the pointer type derived from the type void, although
that is a convenience, there is no real relationship between void and
void * (for example you cannot dereference a void * pointer in a valid C
program).

Quote:
>I'm not sure it's really a type in that case, although it's not a
>special-case production in the grammar.

>Another use: expressions can be cast to void types.  This is
>sometimes seen done to the return value of a function to
>explicitly indicate that its result is being thrown away.

It is permitted for both of the final 2 operands of the ?: conditional
operator to have type void. An operand (and indeed any expression) always
has a type.

--
-----------------------------------------


-----------------------------------------



Mon, 16 Aug 2004 06:18:26 GMT  
 problem with "void"


Quote:
> "The lusers I know are so clueless, that if they were dipped in clue
>  musk and dropped in the middle of pack of horny clues, on clue prom
>  night during clue happy hour, they still couldn't get a clue."
> --Michael Girdwood, in the monastery

Best Quote Ever.

-Daniel



Mon, 16 Aug 2004 08:13:15 GMT  
 problem with "void"

Quote:

> > {
> >   void *foo=malloc(sizeof(int));
> >   foo = (int *) foo;
> >   printf ("%d", foo);

> I think you mean
>    printf("%p", (void *)foo);

foo is already of type (void *), the cast is unnecessary.

--
Simon.



Mon, 16 Aug 2004 08:59:58 GMT  
 
 [ 21 post ]  Go to page: [1] [2]

 Relevant Pages 

1. What's The Difference Between "typedef void *" and "void *"??

2. "void main" is a lifestyle choice

3. what is "static void usage()"?

4. printf("%p\n",(void *) ptr);

5. remove() vrs fopen("""w")

6. Displaying binary data as ascii "1"'s and "0"'s

7. Looking for "Shroud"/"Obfus"

8. ""help with TSR""

9. Parse trees and "("")"

10. Error "free"-ing "malloc"-ed memory

11. Displaying binary data as ascii "1"'s and "0"'s

12. Attention "C"/"C++" gurus and "C" newbees

 

 
Powered by phpBB® Forum Software