Jiminion Jiminion - 3 months ago 13
C Question

Use of malloc in Pthreads

This is actual 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 to malloc *parms instead of ThreadParms. It looks like it is allocating only a pointer (which would be an error), but it apparently allocating the size of the whole structure. Is this correct?

Answer

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

The rationale is as follows: if you have

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

and then change some_type to some_other_type, the code would continue working fine with only one change.

However, if you start with

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

then you have to change some_type in two places:

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

or your code would have an error.

It looks like it is allocating only a pointer (which would be an error)

The asterisk makes sizeof evaluate to the size of the entire struct, so the code is correct.