Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 354
Jiminion Avatar asked Dec 11 '22 15:12

Jiminion


1 Answers

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.

like image 120
Sergey Kalinichenko Avatar answered Dec 26 '22 15:12

Sergey Kalinichenko