cerror-handling

Segmentation fault (core dumped) Error, no line reference


I am receiving the "Segmentation fault (core dumped)" error. This code was working earlier, and I am at a lost what is causing this. Any pointers would be greatly appreciated. This error provides no line reference either.

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

int assignX(int nCol, int nRow, double *Xflat, char *fileName);

int main(){
   FILE *f;
   char myStr[1000];
   int strL;
   int nCol;
   int nRow;
   char *fileName = "reg.dat";
   int i, j, k, z, n1=nCol, n2=1, info;

   double *Xflat;
   double *temp;

   f = fopen(fileName, "r");
   if (f == NULL) perror ("Error opening file");
   else {
     if (fgets(myStr, 1000, f) != NULL )
       puts(myStr);
     fclose(f);
   }

   strL = strlen(myStr);
   nCol = 3;
   nRow = 150;
   printf("Sample size and number of predictors are %d and %d respectively.\n", nRow, nCol-1);

   assignX(nCol, nRow, Xflat, fileName);

   return 0;
}

int assignX(int nCol, int nRow, double *Xflat, char *fileName){
  int i=0;
  int j;
  int k=0;
  char string[1000];
  char* data = NULL;
  FILE *f;
  f = fopen(fileName, "r");

  while(fgets(string, sizeof(string), f) != NULL){
    data = strtok(string, " ");
    for (j=0; NULL != data && j<nCol; j++){
        if (data[strlen(data) - 1] == '\n')
            data[strlen(data) - 1] = '\0';

        if (j!=0){
          Xflat[i] = atof(data);
          i++;
        }
        data = strtok(NULL, " ");
    }
  }

  for (i=0;i<(nRow*(nCol-1));i++){
    printf("%f\n", Xflat[i]);
  }

  return 0;
}

Solution

  • The problem here is, you're using double *Xflat; uninitialized. Accessing uninitalized memory invokes undefined behaviour which in turn may cause segmantation fault.

    You need to allocate memory to double *Xflat; before using it.

    A Suggestion: Enable -g flag while compiling and run your binary through a debugger like gdb. Most of the time in pinpoints the error to the specific line number itself.