I am trying to fix my function where I set the Nth bit of an already allocated space. If the size of N is larger than the size of space malloc'd then reallocate more space to be able to set the Nth bit.
My issue is that whenever I set a bit higher than the space allocated it sets two bits. I have been playing with it for a bit now and I feel stumped. I feel like the issue lies with using realloc incorrectly?
An example is when I try to set the 52nd bit it results with this output:
0001 0000 0000 0000 0000 0000 0000 0000 0001 0000 0000 0000 0000 0000
Both the 52nd bit and 20th bit are set
I made a repl.it of my whole program here: https://repl.it/@dholton/Broken
More specifically here is my function:
Status bit_flags_set_flag( BIT_FLAGS hBit_flags, int flag_position ) {
bits *phBit_flags = ( bits * ) hBit_flags ;
int *new_data = NULL ;
if ( flag_position < phBit_flags -> capacity ) {
// Check to see if the bit request to set is lower than the memory allocated.
*phBit_flags -> data |= ( 1 << flag_position ) ;
} else if ( flag_position >= phBit_flags -> capacity ) {
// The bit requested is larger so realloc new data to reach the length of the requested bit.
new_data = ( int * ) realloc( phBit_flags -> data, ( flag_position / 8 ) + 1 ) ;
if ( new_data == NULL ) {
free( new_data ) ;
return FAILURE ;
}
free( phBit_flags -> data ) ;
phBit_flags -> data = new_data ;
phBit_flags -> size = flag_position ;
phBit_flags -> capacity = ( flag_position / 8 + 1 ) * 8 ;
// capacity is number of bits
*phBit_flags -> data |= ( 1 << flag_position ) ;
// Set nth bit
return SUCCESS ;
}
return FAILURE ;
}