Программирование на C - fgets() бесконечный цикл while

У меня проблема с получением расширенной матрицы из текстового файла. Программа просто выдаст ошибку после успешного считывания всех данных из текстового файла, скорее всего, потому, что она все еще ищет другой токен для достижения или fgets() не достигает состояния NULL? Я честно потерялся...

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include "apmatrix.h"
#define NUMARGS 2 
#define BUFSIZE 128

int main (int argc, char *argv[]) 
{ 
    /* Matrices that will always be used */
    Matrix* A;
    Vector* b;
    Vector* x;
    iVector* p;

    /* Used in LU factorization */
    Matrix* L;
    Matrix* U;

    /* Standard character read-in variables needed */
    char sep[] = " "; /* parsing separator is space */
    char *z,*buffer;  /* buffer and pointer to scan buffer */
    FILE *ifp;        /* source file */ 
    unsigned buflen;  /* length of line read */
    int flag, count;
    int Rows,Columns;/* to hold number read */
    int CurrentRow=0;

    /* first check to see if have required number for argc */ 
    /* if not, error has occurred, don't do anything else */ 
    if (argc == 2 || argc==3) 
    { 
        /* correct number of arguments used, try to open both files */ 
        buffer = (char*) malloc(BUFSIZE); /* allocate buffer */
        ifp = fopen (argv[1], "r");  /* open file for reading */ 

        if (ifp && buffer) { /* if successful proceed */
            /* read file line by line */
            flag=0;
            while (fgets(buffer, BUFSIZE, ifp) != NULL) {       
                /* defensive/secure programming */
                buflen = strlen(buffer);
                /* parse line */            
                z = strtok(buffer,sep);

                /* take in the values of the rows and columns */
                if(flag == 0){
                    ++flag;                 /* Flag = 1 */

                    Rows = atoi(z);         /* Convert the string to double */
                    printf("  %d",Rows);
                    z = strtok(NULL, sep);  /* find next number */
                    Columns = atoi(z);      /* Convert the string to double */           
                    printf("  %d",Columns);
                    putchar('\n');

                    A = m_alloc(Rows,Columns);
                    b = v_alloc(Rows);
                    x = v_alloc(Rows);
                    p = iv_alloc(Rows);

                    L = m_alloc(Rows,Columns);
                    U = m_alloc(Rows,Columns);
                }
                /* take in the values of the matrices */
                else{

                    for(int i = 0; i < Rows; i++){
                        A->mat[CurrentRow][i] = (Real) atof(z);             /* Convert the string to an int*/
                        z = strtok(NULL, sep);  /* find next number */
                        printf("   %2.3f   ",A->mat[CurrentRow][i]);
                    }

                    b->vec[CurrentRow] = (Real) atof(z);            /* Convert the string to an int */
                    printf("   %2.3f   ",b->vec[CurrentRow]);           
                    putchar('\n');
                    CurrentRow++;
                    putchar('\n');
                }

            } 
            fclose (ifp); 

...

Я не распечатывал остальную часть своего кода, потому что просто не вижу, чтобы он имел отношение к рассматриваемому вопросу. Я хочу знать, почему возникает эта проблема и как я могу исправить ее в коде, потому что мне понадобится информация для решения Ax=b позже в программе. Текстовый файл дает мне расширенную матрицу [A|b], поэтому я решаю для x, используя факторизацию LU. Я думаю, что это может быть связано с самим буфером, но я также неопытен в программировании на C.

Также текстовый файл, который я читаю, написан как таковой...

 3 4
 2 1 1  1
 6 2 1 -7
-2 2 1  7 

Это результаты, которые я получаю от кода

  3  4
   2.000      1.000      1.000      1.000

   6.000      2.000      1.000      -7.000

   -2.000      2.000      1.000      7.000

Segmentation fault (core dumped)

Спасибо за ваше время. :)

ОБНОВЛЕНИЕ: я попытался запустить gdb для отладки, и я застрял, пытаясь запустить дамп ядра с текстовым файлом. (например, ./hw6 ge1.txt — это то, что я ввожу в командную строку). Как мне запустить это с текстовым файлом, потому что без него он segfaulting.

 c
Continuing.
Expecting two or three arguments
The second argument must be a text file to read from.
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400a4e in m_free (M=0x0) at apmatrix.c:32
32              free(M->mat[0]); /* free data */

person Challice Genest    schedule 16.04.2015    source источник
comment
Подключить GDB и попытаться найти строку, вызывающую сбой?   -  person Prabhu    schedule 16.04.2015
comment
Бесконечный цикл или ошибка сегментации? У вас не может быть обеих проблем.   -  person Some programmer dude    schedule 16.04.2015
comment
z = strtok(NULL, sep); Columns = atoi(z); не проверяет, z === NULL.   -  person chux - Reinstate Monica    schedule 16.04.2015
comment
Попробуйте проверить, равен ли буфлен 0! Если это 0, вы не выполняете синтаксический анализ строки (я думаю, что вы можете сломать время, но я не уверен, что это правильно! Но если вы видите, что программа остается в цикле после того, как buflen становится 0, то чтобы сломать время это правильный путь).   -  person Sir Jo Black    schedule 16.04.2015


Ответы (1)


1) compile your program with -ggdb parameter
2) link your program with the -ggdb parameter

Это приведет к созданию исполняемого файла, содержащего максимальное количество отладочной информации, которую может использовать отладчик gdb.

3) assure the source code is visible from where the program is to be run
   (in the same directory works very well)
4) at the command line: gdb yourProgramName
5) from within gdb enter the following commands
    br main    <-- sets breakpoint at main
    run        <-- execution program until breakpoint reached
    c          <-- continue execution
6) when the program crashes, enter the following commands
   bt          <-- display a back trace
7) examine the back trace to see which line your program crashed on.

8) quit y      <-- to exit the program
9) let us know which line that is.  
   paste/edit the line into your question
   as a line number would be meaningless to us.
person user3629249    schedule 16.04.2015