People‎ > ‎John Stavrakakis‎ > ‎John's blog‎ > ‎

Mixed C/C++ array reset

posted 13 Dec 2011, 00:40 by John Stavrakakis
Just thought I'd share something that caused me a little trouble. When mixing C and C++ code, you cannot assume NULL == 0. Unfortunately, my Linux gcc dev days showed me that this is the case. 

/* init */
void **ptrarray = (void**)malloc(n * sizeof(void*));

/* bad reset. Does not work */
memset( ptrarray, 0x00, n); 

/* good reset */
for (i =0; i < n; ++i)
  ptrarray[i] = NULL;

In C, NULL is not guaranteed to be (void*)0 on all systems! I was always favourable to memset for compiler optimisation. Fool!

stddef.h OS X 10.7

#undef NULL

#ifdef __cplusplus

#undef __null  // VC++ hack.

#define NULL __null


#define NULL ((void*)0)


memset should only be reserved for char, short, integer, long. Assuming the float and double have zero bits to mean 0.0 could also fail, more importantly zeroing out the structs with non-integer and now pointer elements requires extra attention.

struct _sample {
    int xyz[3];
    float fxyz[3];
    int ijk[3];
} smp;

To try and use memset here would also be system dependent on the struct layout. The only option is to reset by assignment:
memset(, 0x00, 3*sizeof(int));
memset(smp.ijk, 0x00, 3*sizeof(int));
smp.fx = 0.0f;
smp.fy = 0.0f;
smp.fz = 0.0f;

All the code I have is strictly C. The C++ mix was necessary to link external dependent libraries. Ah the joys.