Using malloc in Pthreads

This is valid C code from Pthreads:

ThreadParms *parms = NULL; 
if ((parms = (ThreadParms *) malloc (sizeof (*parms))) == NULL)
    {
      goto FAIL0;
    }

  parms->tid = thread;
  parms->start = start;
  parms->arg = arg;

Why did they choose marmoc * parms instead of ThreadParms? It looks like it only highlights the pointer (which would be an error), but it seems to highlight the size of the whole structure. Is it correct?

+4
source share
3 answers

This is a common trick in C - using the dereference pointer expression instead of the actual type.

The rationale is: if you have

some_type *some_var = malloc(sizeof(*some_var));

and then change some_typeto some_other_type, the code will continue to work fine with just one change.

However, if you start with

some_type *some_var = malloc(sizeof(some_type));

then you have to change some_typein two places:

some_other_type *some_var = malloc(sizeof(some_other_type));

or your code will have an error.

, ( )

sizeof struct, .

+5

*parms ThreadParms,

, , sizeof(ThreadParms), , parms , ( sizeof )

( / , )

+3

marmoc * parm ThreadParms.

, parms , . ThreadParms .

, ( ), , -, . ?

No. This is actually equivalent to using sizeof(ThreadParms), as the sizeof operator is only required information about the type and it does not evaluate its operand (except C99 variable-length arrays ). Type *parmsis equal ThreadParmsand what everyone sizeofshould know.

Side note: casting to is ThreadParms *not required in C since void *any other data pointer can be assigned.

+3
source

Source: https://habr.com/ru/post/1653943/


All Articles