Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to zero an array of pointers

I am allocating memory for a pointer array. The result has a fixed number of items and I want all of them initialised to NULL.

char **result = (char **)calloc(12, sizeof(char *));

Can I now be sure that elements result[0] to result[11] are NULL?

like image 458
Bart Friederichs Avatar asked Aug 09 '26 23:08

Bart Friederichs


1 Answers

As 0-ing out a pointer p's value by doing

memset(p, 0, sizeof(p));

not necessary needs to be equal to doing

p = NULL;

on each and every platform, you'd be on the safe side doing:

SomeType ** result = malloc(12 * sizeof(*result));
if (NULL != result)
{
  for (size_t i = 0; i < 12; ++i)
  {
    result[i] = NULL;
  }
}

You could wrap this in a macro like so:

#define ALLOCARRAY(result, size) \
  do { \
    result = malloc(size * sizeof(*result)); \
    if (NULL != result) \
    { \
      for (size_t i = 0; i < size; ++i) \
      { \
        result[i] = NULL; \
      } \
    } \
  } while (0)

Then use the macro like this:

#include <stdlib.h>

[...]

SomeType ** result = NULL;
ALLOCARRAY(result, 12);
if (NULL == result)
{
  /* Handle error here. */
}
else 
{
  /* Use array here. */

  /* Free array. */
  free(result);
}
like image 104
alk Avatar answered Aug 11 '26 15:08

alk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!