Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I allocate a specific number of bits in C?

Tags:

c

malloc

bitmask

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?

like image 261
Tim Avatar asked Nov 12 '08 16:11

Tim


People also ask

Does C have memory allocation?

In C, dynamic memory is allocated from the heap using some standard library functions. The two key dynamic memory functions are malloc() and free(). The malloc() function takes a single parameter, which is the size of the requested memory area in bytes. It returns a pointer to the allocated memory.

Does malloc use bits or bytes?

In dlmalloc , the smallest allowed allocation is 32 bytes on a 64-bit system. Going back to the malloc(1) question, 8 bytes of overhead are added to our need for a single byte, and the total is smaller than the minimum of 32, so that's our answer: malloc(1) allocates 32 bytes.

How many bits an integer variable occupies in memory?

1 Integers. Integers are commonly stored using a word of memory, which is 4 bytes or 32 bits, so integers from 0 up to 4,294,967,295 (232 - 1) can be stored.


1 Answers

...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]

element is addressing bytes, not bits. You want something like:

pStatus[element/8] & (1 << (element % 8))
like image 162
Ana Betts Avatar answered Sep 22 '22 12:09

Ana Betts