hypocentrum
hypocentrum

Reputation: 11

Segmentation Fault Core dump with C on ubuntu

I have a problem with some line of codes I've written in plain C. It worked fine on windows, but on ubuntu there's an error saying "Segmentation Fault (core dumped)". I've searched for answers but there's too many problem that can caused that error.

char line[80];
char sett[50][80];
int index=0;
static const char filename[] = "squid.conf";
FILE *file = fopen ( filename, "r" );

while ( fgets ( line, sizeof line, file ) != NULL ) 
{
    strcpy(sett[index],line);
    index++;
}

I just simply want to write the whole file to an 2 dimensional array, line by line. If I quote the //strcpy(sett[index],line); the program runs fine with no errors.

Upvotes: 1

Views: 2816

Answers (1)

David Ranieri
David Ranieri

Reputation: 41017

As others have said, maybe your squid.conf have more than 50 lines, (my squid.conf have 4948 lines)

You can count lines before and malloc(nlines * 80) or you can use a linked list:

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

typedef struct sett {
    char value[80];
    struct sett *next;
} sett;

int main(void)
{
    char line[80];
    sett *curr, *first = NULL, *prev = NULL;
    static const char filename[] = "squid.conf";
    FILE *file = fopen(filename, "r");

    while (fgets(line, sizeof line, file) != NULL) {
        curr = malloc(sizeof(sett));
        if (curr == NULL) {
            perror("malloc");
            exit(EXIT_FAILURE);
        }
        if (prev) {
            prev->next = curr;
        } else {
            first = curr;
        }
        strcpy(curr->value, line);
        curr->next = NULL;
        prev = curr;
    }
    fclose(file);
    curr = first;
    while (curr) {
        printf("%s", curr->value);
        prev = curr;
        curr = curr->next;
        free(prev);
    }
    return 0;
}

Upvotes: 1

Related Questions