Search code examples
cclion

Getting a segmentation fault in C with unsigned long long int?


Im trying to code a decimal to binary converter in C. I have to use unsigned long long int because the largest number I have to be able to calculate is 18,446,744,073,709,551,615. On the Linux server my professor has us use, it says there is a segmentation fault, and on CLion debugger it says "Exception = EXC_BAD_ACCESS (code=2, address=0x7ff7bc694ff8)" and claims i = {unsigned long long} 18446744073708503289, which isn't right. It does this no matter what number userInput is.

What I currently have:

#include <stdio.h>

int main(void)
{
  unsigned long long int userInput;
  unsigned long long int i;
  unsigned long long int binary[] = {};

  printf("Enter a number from 0 to 18,446,744,073,709,551,615: ");
  scanf("%lld", &userInput);

  printf("\nThe binary value of %lld is: ", userInput);

  if (userInput == 0)
  {
      printf("0");
  }
  else
  {
    for (i = 0; userInput > 0; i++)
    {
        binary[i] = userInput%2;
        userInput = userInput/2;
    }
    for (i -= 1; i >= 0; i--)
    {
        printf("%lld", binary[i]);
    }
  }

  printf("\n");

  return 0;
}

Solution

  • Because binary was not given an explicit size and was given an empty initializer list, the array has size 0. Any attempt to use such an array will trigger undefined behavior which in this particular case causes a crash.

    You need to store up to 64 binary digits, so make the array that size.

    unsigned long long int binary[64];
    

    Another problem is in this conditional:

    for (i -= 1; i >= 0; i--)
    

    Because i has an unsigned type, the condition i >= 0 will always be true. So change the type of i to int.

    int i;