2016-11-04 43 views
-1

這裏是一個將實現公式(1 + x)^ 2的代碼:在Linux上的gcc爲下面的代碼獲取分段錯誤。我無法弄清楚我要去哪裏錯了

#include <stdio.h> 
#include <stdlib.h> 
#include "nCr.h" 
#include <time.h> 
#include <sys/time.h> 

int main(int argc, const char * argv[]) 
{ 
    int k = 0; 
    int n; 
    int c; 

    struct timeval start, end; 

    if (argv[1][0] == '-' && argv[1][1] == 'h') { 
     printf("Usage: formula <positive integer>"); 
    } else { 
     n = atoi(argv[1]); 

     // gettimeofday will give the execution time of program in microsecond. 

     gettimeofday(&start, NULL); 

     printf("(1 + x)^%i = ", n); 

     if (n == 0) 
      printf("0"); 

     for (; k <= n; k++) { 

      // Here nCr is an assembly code which compute coefficient 

      c = nCr(n, k); 

      if (c == -1) { 
       printf("Multiplication overflow. \n"); 
       return 1; 
      } else { 
       if (k != 0) 
        printf("%i x^%i ",c , k); 

       if (k != n && k != 0) 
        printf("+ "); 
      } 
     } 

     gettimeofday(&end, NULL); 

    } 

    printf("\n%ld microseconds\n", ((end.tv_sec * 1000000 + end.tv_usec) 
      - (start.tv_sec * 1000000 + start.tv_usec))); 

    return 0; 
} 

得到分段錯誤

+0

通過使用調試器來捕捉崩潰「實際行動」以找到它在代碼中發生的位置。 –

回答

2

它可能因爲您嘗試訪問不存在的參數而發生。在訪問參數之前添加argc檢查。

相關問題