将文件加载到C上的链接列表中,有时可以工作,有时也不会

时间:2015-05-28 09:06:56

标签: c list crash dynamic-memory-allocation

这是我用来加载它的函数,有时它可以工作但是当我离开程序并再次编译时,它会崩溃:

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

//this is how I declared the list
struct plantillas {
    int iduser;
    int idplant;
    char name[31];
    int pres;
    int punt;
    struct plantillas *next;
};
struct plantillas *first, *last;

//This is the main that calls loadfile:
int main(){
    FILE *file;
    file = fopen("Plantillas.txt", "r");
    puts("a");
    load_file(file);
    fclose(file);
}

//this is the funcion that actually loads the file
void load_file(FILE *file) {
    char cadaux[100];
    first = (struct plantillas *) NULL;
    last = (struct plantillas *) NULL;
    struct plantillas *new;

    while (!feof(fichero)){
        /* save memory for the new element on the list */
        new = (struct plantillas *) malloc(sizeof(struct plantillas));
        if (new == NULL) printf("No memory avaiable!\n");
        fflush(stdout);

        readline(file, cadaux); //I'll explain about this later
        sscanf(cadaux, "%d %d %s %d   %d", &new->iduser, &new->idplant, new->name, &new->pres, &new->punt);

        new->next = NULL;

        /* this will find out if the linked list is empty or not */
        if (first == NULL) {
            first = new;
            last = new;
        }
        else {
            /* if it isn't, the one that was last before now has to point to the next element on the list */
            last->next = new;
            /* now we make the new be the last */
            last = new;
        }
    }
}

/*The readline function is because of format issues. As it is an    assignment for school, the format of the file has to be in1-int2- string1-int3-int4, readline reads each line on the file and turn the '-' into ' ' and then saves it into an auxiliary string. Here is the function:*/

void readline(FILE * a, char * b)
{
    int i;
    fscanf(a, "%s", b);
    for (i = 0; b[i] != '\n'; i++)
    {
        if (b[i] == '-') b[i] = ' ';
    }
}

对不起,如果有一些变量完全匹配,我翻译了西班牙语的代码,试着让它更容易理解。此外,对于格式化问题感到抱歉,这是我在这里的第一篇文章,我遇到了一些麻烦

1 个答案:

答案 0 :(得分:1)

代码中有两个主要错误会导致问题。

首先,您不应该while (!feof(...)),因为在您尝试从文件之外读取之前,EOF标志未设置,导致循环迭代一次到多次。这很糟糕,但不是致命的,因为它所做的就是让你最后用虚拟数据添加一个额外的节点。

第二个也是绝对致命的错误是你使用fscanf来读取一个不包含换行符的字符串(或者根本就没有任何空格),然后在写入换行符时查找换行符缓冲。因为您读取的字符串不包含换行符,所以fscanf之后的循环将超出缓冲区的末尾,并且您很可能会在堆栈的某处写入数据导致未定义的行为。该循环的正确条件是查找字符串终止符'\0'

我解决这两个问题的建议是没有readline函数,而是使用fgets代替,并使用while (fgets(cadaux, sizeof(cadaux), file) != NULL)作为循环条件,并使用函数替换带有空格的'-'个字符,并在该函数中检查两个换行符和循环中的字符串终止符。

相关问题