memset and bool

So, I was trying a primality test program using good old C to have some retro feeling. Got burnt very bad with the memset.

Jut to jog your memory, memset accepts following parameters:
ptr -Pointer to the block of memory to fill.
value -Value to be set. The value is passed as an int, but the function fills the block of memory using the unsigned char conversion of this value.
num -Number of bytes to be set to the value.

More details here: http://www.cplusplus.com/reference/cstring/memset/

What I wanted to do is set an array with true. As you might be aware that C standards earlier to C98 (C89 etc.) didn’t had any bool type. So I created an enum version of it.

typedef enum
{
false,
true=!false
} bool;

What I forgot, is that enum by default using storage space equivalent to int. So when I tried to initialize my array as following:

memset(prime, true, sizeof(prime));

It bombed!
What the array contained 16843009 for all its element.
Now,  16843009 = (01010101)16. So clearly, what memset did was to copy 1 repeatedly to each byte of the integer array element (which was of 4 bytes on my machine).

Is using C98 with stdbool header the right answer?
It mostly is. But, like other data types, C doesn’t set an upper bound to bool’s size. All it guarantees it to be not smaller than byte (GCC defies_Bool as 1 byte). But it could be anything larger. So, the GERD continues.
*Note: Safest way is to loop through the array to set it’s value.

Leave a Reply