question about malloc and sizeof *foo 
Author Message
 question about malloc and sizeof *foo

howdy

I've seen several people here refer to this construct for using malloc:

char *foo = malloc(8 * sizeof *foo);

the question that pops to mind is:  isn't this dereferencing foo before
foo has been allocated?  i.e. a no-no?

Or is the compiler smart enough to not actually dereference foo in this
case?



Sat, 27 Sep 2003 14:26:35 GMT  
 question about malloc and sizeof *foo

Quote:
> howdy

> I've seen several people here refer to this construct for using malloc:

> char *foo = malloc(8 * sizeof *foo);

> the question that pops to mind is:  isn't this dereferencing foo before
> foo has been allocated?  i.e. a no-no?

> Or is the compiler smart enough to not actually dereference foo in this
> case?

It's not the compiler, but the language itslef.

From the C99 standard:
6.5.3.4 The sizeof operator

2    ... If the type of the operand is a variable
     length array type, the operand is evaluated;
     otherwise, the operand is not evaluated ....

So onlyif you need to calculate the size of an
array, the operand will be evaluated, in no other
case. This means, That the *foo given to sizeof
is not evaluated, the size of an object pointed
to by foo is determined from the type of that object.

--

"LISP  is worth learning for  the profound enlightenment  experience
you will have when you finally get it; that experience will make you
a better programmer for the rest of your days."   -- Eric S. Raymond



Sat, 27 Sep 2003 14:57:15 GMT  
 question about malloc and sizeof *foo

Quote:

>I've seen several people here refer to this construct for using malloc:

>char *foo = malloc(8 * sizeof *foo);

>the question that pops to mind is:  isn't this dereferencing foo before
>foo has been allocated?  i.e. a no-no?

>Or is the compiler smart enough to not actually dereference foo in this
>case?

Normally you would be right, however, a (to some people)
subtle aspect of the sizeof operations is that is does
not evaluate the expression (value-wise that is, type-wise it does).
--
Greg Comeau                 Comeau C/C++ 4.2.45.2 "it's so close"
ONLINE COMPILER ==>         http://www.comeaucomputing.com/tryitout
NEW: Try out libcomo!       NEW: Try out our C99 mode!



Sat, 27 Sep 2003 21:34:04 GMT  
 
 [ 3 post ] 

 Relevant Pages 

1. sizeof(foo) -1 or sizeof(foo)

2. sizeof(void*) versus sizeof(foo*)

3. makefile question - foo.c := DUMMY=foo

4. newbie question: foo.exe ->foo.c ??

5. malloc(sizeof(char)) problem

6. malloc(sizeof(char)) problem

7. malloc(sizeof(char)*12)

8. difference between void foo(void) and void foo()

9. malloc(sizeof(type))

10. sizeof vs. strlen and malloc()

11. extern char *foo vs. extern char foo[]

12. malloc() and sizeof

 

 
Powered by phpBB® Forum Software