c - Use of malloc in Pthreads -
this actual c code pthreads:
threadparms *parms = null; if ((parms = (threadparms *) malloc (sizeof (*parms))) == null) { goto fail0; } parms->tid = thread; parms->start = start; parms->arg = arg;
why did choose malloc *parms instead of threadparms? looks allocating pointer (which error), apparently allocating size of whole structure. correct?
this common trick in c - using dereference pointer expression in place of actual type.
the rationale follows: if have
some_type *some_var = malloc(sizeof(*some_var));
and change some_type
some_other_type
, code continue working fine 1 change.
however, if start with
some_type *some_var = malloc(sizeof(some_type));
then have change some_type
in 2 places:
some_other_type *some_var = malloc(sizeof(some_other_type));
or code have error.
it looks allocating pointer (which error)
the asterisk makes sizeof
evaluate size of entire struct
, code correct.
Comments
Post a Comment