简体   繁体   中英

Getting segmentation fault for the code below. I am not able to figure out where am I going wrong

Here is the code that will implement the formula (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;
}

getting segmentation fault on Linux gcc

It may happen because you try to access arguments that doesn't exist. Before accessing arguments add argc check.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM