segmentation fault (core dumped) in C program to make histogram

Viewed 54

I am trying to write a program that shows a histogram. I keep getting segmentation fault (core dumped) each time I run it. I am reading in a file with numbers in it and trying to find the occurrences of each number and to print a histogram from it. I have looked all over but can not seem to find why this is happening. Please tell me why.

INPUT random.txt

1405413042132140413140

DESIRED OUTPUT

0 ****
1 ******
2 ** 
3 ***
4 ******
5 *
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <unistd.h>

int main(int argc, char *argv[]){
    int n = 1001; 
    int a[n];
    int opt;

    FILE *f;
    if(argc == 5){
        f = fopen(argv[5], "r");
    }
    else if(argc == 4){
        f = fopen(argv[4], "r");
    }
    else if(argc == 3){
        f = fopen(argv[3], "r");
    }
    else if(argc == 2){
        f = fopen(argv[2], "r");
    }
    else if(argc == 1){
        f = fopen(argv[1], "r");
    }
    else if(f == NULL){
        printf("ERROR: File Not Found\n");
        return 1;
    }
}
1 Answers

Since array indexes start at 0, the last argument in argv is argv[argc-1]. Your code is trying to use argv[argc] as the filename, but this element always contains a null pointer, which is causing the segmentation fault when you call fopen().

You should also notice the pattern in all your if statements, which allows you to combine them all into a single line.

int main(int argc, char *argv[]){
    int n = 1001; 
    int a[n];
    int opt;
    struct options opts = {60, '*', 3, '\n'};
    while((opt = getopt(argc, argv, "s:m:c:w:n") != -1)){
        switch(opt){
        case 's':
            opts.scale = atoi(optarg);
            break;
        case 'm':
            opts.c = optarg[0];
            break;
        case 'w':
            opts.width = atoi(optarg);
            break;
        case 'n':
            opts.bars = 0;
            break;
        default:
            fprintf(stderr, "Valid options are s,m,c,w,n\n");
            exit(1);
        }
    }
    
    if (argc < 2) {
        printf("ERROR: filename is required\n");
        return 1;
    }
    FILE *f = fopen(argv[argc-1], "r");
    if (f == NULL){
        printf("ERROR: File Not Found\n");
        return 1;
    }
    
    count(f, a, n);
    max(n, a);
    histogram(n, a, &opts);
}
Related