Parambir Grewal Parambir Grewal - 1 month ago 10
C Question

Why am I getting a segmentation fault at runtime?

I am trying to read the names from a file, store them in a dynamically allocated character array then print them to the console. When I run the program I get a segmentation fault. I think it has something to do with fgets. Why is this happening?

votes.txt:

Almog, Nat
Ngoc, Noor
Hyun-Joo, Candide
Ji, Yarden
Celestine, Maui
Li, Cande
Tristen, Thoko
Vijaya, Cheng
Jaya, Sung-Hyun
Glaw, Cahya


main.c:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv) {
FILE* fp;

fp = fopen("votes.txt","r");

char** nameArray = malloc(10 * sizeof(char *)); //Allocate row pointers

int i;
for(i =0; i< 10; i++) {
nameArray[i] = malloc(25 * sizeof(char)); //Allocate each row separately
}
int j;
for(j=0;j<10;j++) {
fgets(nameArray[i], 25, (FILE*)fp);
}

int l;
for (l=0; l<10; l++) {
printf("nameArray[%d] = %s\n",l,nameArray[l]);
}

int k;
for (k =0; k<10; k++) {
free(nameArray[i]);
}
free(nameArray);
}

Answer

Your indices are wrong in a few places:

int j;
for(j=0;j<10;j++) {
    fgets(nameArray[j], 25, (FILE*)fp);

int k;
for (k =0; k<10; k++) { 
    free(nameArray[k]);

Both of these have i for the array indices in the loops of your code. I am not sure why you are using i, j, k, and l anyway. Why not just use i? This would have saved you some confusion.

You should also close(fp), and add return 0 at the end of main().