【发布时间】:2022-01-14 03:52:31
【问题描述】:
我正面临分段错误的问题。我知道这与记忆有关。 我做了一些更改,但一直出错。我正在尝试读取一个 25kb 的大文件。 我需要阅读一个最大的 csv 并将其逐行放入结构中。我用链表做到了。 我已经尝试过使用列表。 如果我在不拆分字符串的情况下读取文件,我没有错误。
#include <string.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
struct gh_user {
char *id;
char *login;
char *type;
char *createdat;
char *followers;
char *followerlist;
char *following;
char *followinglist;
char *public_gists;
char *pub_repos;
struct gh_user *next;
};
typedef struct gh_user *GH_USER;
void separador (char *lines, GH_USER k) {
k->id = strdup(strsep(&lines, ";"));
k->login = strdup(strsep(&lines, ";"));
k->type = strdup(strsep(&lines, ";"));
k->createdat = strdup(strsep(&lines, ";"));
k->followers = strdup(strsep(&lines, ";"));
k->followerlist = strdup(strsep(&lines, ";"));
k->following = strdup(strsep(&lines, ";"));
k->followinglist = strdup(strsep(&lines, ";"));
k->public_gists = strdup(strsep(&lines, ";"));
k->pub_repos = strdup(strsep(&lines, ";"));
free(lines);
}
int conta_bots()
{
FILE *usr;
usr = fopen("../entrada/users.csv","rb");
int contador = 0;
char *lines = malloc(1024);
GH_USER k = malloc(sizeof(struct gh_user));
int fileSize = 0;
while (fgets(lines, 1024,usr)!=NULL)
{
if(lines != NULL)
{
separador (lines,k->next);
printf("%s", k->type);
}
}
free(k);
fclose(usr);
free(lines);
return contador;
}
int main()
{
conta_bots();
return 0;
}
【问题讨论】:
-
能分享一下调试结果吗?
-
还有其他问题,例如:
if(lines != NULL):此检查毫无意义。typedef struct gh_user *GH_USER;: 不要在 typedef 后面隐藏指针类型,这只会造成混乱。 -
实际上释放未分配的指针是未定义的。
strsep将lines的值更新为与其开始时不同的地址,因此free(lines)可能会表现出未定义的行为。 -
最好使用调试器找出它落在哪一行。如果您对代码进行了更改,请edit您问题中的代码,并在必要时更新观察到的行为。
-
如果您有新代码和/或新信息,请将其添加到您的问题中。不要删除旧内容,因为这会使 cmets 和(可能)答案无用。