I am trying to run this piece of code where I get input "message" from a user and I turn that message to binary code. I later print this as lit bulbs for 1 and dark ones for 0 with emojis. However, I keep getting 'segmentation fault (core dumped)' after I enter my input on the terminal. Does anyone know why, and what does it mean in this particular case? Thank you!
int main(void)
{
// prompt for message
string message = get_string("message: ");
int len = strlen(message);
for (int i = 0; i < len; i++)
{
int value = message[i];
int binary_code[BITS_IN_BYTE];
// convert to binary
for (int j = 0; j < BITS_IN_BYTE; j++)
{
int rem;
int place = BITS_IN_BYTE - j;
rem = value % 2;
binary_code[place] = rem;
value /= 2;
}
// print bulbs
for (int k = 0; k < BITS_IN_BYTE; k++)
{
print_bulb(binary_code[k]);
}
printf("\n");
}
}
At least there is the following problem with your code.
You declared an array with BITS_IN_BYTE
elements
int binary_code[BITS_IN_BYTE];
So the valid range of indices is [0, BITS_IN_BYTE)
.
However when j
is equal to 0
in this for loop
for (int j = 0; j < BITS_IN_BYTE; j++)
{
int rem;
int place = BITS_IN_BYTE - j;
rem = value % 2;
binary_code[place] = rem;
value /= 2;
}
then the value of the variable place
is equal to BITS_IN_BYTE
int place = BITS_IN_BYTE - j;
As a result this statement
binary_code[place] = rem;
writes to memory outside the array that results in undefined behavior.
You should initialize the variable place
the following way
int place = BITS_IN_BYTE - j - 1;