为下面的代码获取分段错误。我无法弄清楚我哪里出错了

时间:2016-11-04 17:27:04

标签: c linux gcc

以下是将实现公式(1 + x)^ 2的代码:

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

在Linux gcc上出现分段错误

1 个答案:

答案 0 :(得分:2)

可能会发生这种情况,因为您尝试访问不存在的参数。在访问参数之前,添加argc check。