Jiminion Jiminion - 1 year ago 97
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 Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download