[PD] fux_kinect

Mathieu Bouchard matju at artengine.ca
Sat Nov 12 18:31:07 CET 2011

Le 2011-11-12 à 17:13:00, Claude Heiland-Allen a écrit :

> A nice idiom for malloc is to use the sizeof of the target of the 
> pointer to which you are assigning its result (no explicit cast needed 
> when assigning from a void * afaik, at least no warnings/errors here 
> with gcc (Debian 4.4.5-8) 4.4.5):
>  struct foo *f = malloc(sizeof(*f));

1. This does not work in C++ because implicit casts from void* are all 
assumed to be mistakes ;

2. In any case, this requires that you did type f in the malloc. The 
problem we have here is because the wrong type name was typed in a sizeof. 
If a wrong type name can be typed there, so can a wrong variable name.

Therefore, either use «operator new», or if you're stuck with C, use a 
macro that does the job for you :

   #define NEW(T) ((T*)malloc(sizeof(T)))

so that if you do a wrong assignment, you will get an error for it :

   struct foo *e = NEW(foo);
   struct foo *f = NEW(typeof(*f));
   struct bar *g = NEW(foo);        // wrong
   struct bar *h = NEW(typeof(*f)); // wrong

   error: cannot convert ‘foo*’ to ‘bar*’ in initialization
   error: cannot convert ‘foo*’ to ‘bar*’ in initialization

But anyway, those mallocs in [fux_kinect] are superfluous because you can 
reserve that amount of RAM directly in fux_kinect by removing the «*».

That goes for nearly any struct that you need to create at the same time 
as another struct, and destroy at the same time as that same struct, and 
never need to change the size of. In order to do that, you need to be able 
to init and finalise separately from malloc/free. That's why the function 
is named pthread_cond_init and not pthread_cond_new, for example.

| Mathieu BOUCHARD ----- téléphone : +1.514.383.3801 ----- Montréal, QC

More information about the Pd-list mailing list