Can I allocate a specific number of bits in C?

Tim picture Tim · Nov 12, 2008 · Viewed 13.3k times · Source

I am trying to store a large amount of boolean information that is determined at run-time. I was wondering what the best method might be.

I have currently been trying to allocate the memory using:

pStatus = malloc((<number of data points>/8) + 1);

thinking that this will give me enough bits to work with. I could then reference each boolean value using the pointer in array notation:

pStatus[element]

Unfortunately this does not seem to be working very well. First, I am having difficulty initializing the memory to the integer value 0. Can this be done using memset()? Still, I don't think that is impacting why I crash when trying to access pStatus[element].

I am also not entirely convinced that this approach is the best one to be using. What I really want is essentially a giant bitmask that reflects the status of the boolean values. Have I missed something?

Answer

The Archetypal Paul picture The Archetypal Paul · Nov 12, 2008
pStatus = malloc((<number of data points>/8) + 1);

This does allocate enough bytes for your bits. However,

pStatus[element]

This accesses the element'th byte, not bit. So when element is more than one-eighth of the total number of bits, you're accessing off the end of the array allocated.

I would define a few helper functions

int get_bit(int element)
{
    uint byte_index = element/8;
    uint bit_index = element % 8;
    uint bit_mask = ( 1 << bit_index);

    return ((pStatus[byte_index] & bit_mask) != 0);
}

void set_bit (int element)
{
    uint byte_index = element/8;
    uint bit_index = element % 8;
    uint bit_mask = ( 1 << bit_index);

    pStatus[byte_index] |= bit_mask);
}

void clear_bit (int element)
{
    uint byte_index = element/8;
    uint bit_index = element % 8;
    uint bit_mask = ( 1 << bit_index);

    pStatus[byte_index] &= ~bit_mask;
}

(error checking on range of element left out for clarity. You could make this macros, too)