簡體   English   中英

使用 unsigned long long int 在 C 中出現分段錯誤?

[英]Getting a segmentation fault in C with unsigned long long int?

我試圖在 C 中編寫一個十進制到二進制轉換器。我必須使用 unsigned long long int 因為我必須能夠計算的最大數字是 18,446,744,073,709,551,615。 在我的教授讓我們使用的 Linux 服務器上,它說存在分段錯誤,在 CLion 調試器上,它說“異常 = EXC_BAD_ACCESS(代碼 = 2,地址 = 0x7ff7bc694ff8)”並聲稱 i = {unsigned long long} 18446744073708503289,其中不對。 無論 userInput 是什么數字,它都會這樣做。

我目前擁有的:

#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;
}

一個問題是這些循環之一永遠無法終止:

  unsigned long long int i;
  // ...
  for (i -= 1; i >= 0; i--)
  {
    printf("%lld", binary[i]);
  }

變量i是無符號的並且永遠不會是負數。 因此i >= 0將始終為真,它將永遠循環,讀取內存,直到它到達內存分段不允許它讀取的內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM