所以我一直试图让程序的这一部分读取包含这种格式的名称和数字的特定文件
name number
等并将它们存储在结构列表中
void read_data(char *filename, list *mylist) {
FILE *file = fopen(filename, "r");
if (file == NULL) {
printf("Can't open file\n");
exit (1);
}
char pass[100];
int order;
char line[1000];
while (fgets(line, 1000, file) != NULL) {
list_element *element = malloc(sizeof(list_element));
sscanf(line, "%s %d", pass, &order);
sprintf(element->password, "%s", pass);
element->count = order;
element->next = NULL;
insert_front(element, mylist);
}
fclose(file);
}
sprintf
不断使程序因段错误而崩溃。我试过了 snprintf
我一直有同样的问题。
我不能使用缓冲区,因为在这个特定任务中我不允许使用 <string.h>
所以strcpy
不是一个选项
结构本身是:
struct list_element {
char *password;
int count;
list_element* next;
};
Valgrind 显示:
==25999== Conditional jump or move depends on uninitialised value(s)
==25999== at 0x4ECC374: _IO_str_init_static_internal (strops.c:51)
==25999== by 0x4EBD6C2: vsprintf (iovsprintf.c:41)
==25999== by 0x4EA1093: sprintf (sprintf.c:32)
==25999== by 0x4008E7: read_data
==25999== by 0x400B80: main
==25999== Uninitialised value was created by a heap allocation
==25999== at 0x4C2FB0F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==25999== by 0x400898: read_data
==25999== by 0x400B80: main
任何关于我的错误所在的提示将不胜感激:)
最佳答案
使用 list_element* element = malloc(sizeof(list_element));
,您正在为列表元素分配空间,但您没有为成员 password< 的密码分配空间
应指向。所以你的 sprintf(element->password,"%s", pass);
将写入你尚未分配的内存。
要么在 sprintf
之前分配空间(顺便说一句:strcpy
也可以完成这项工作):
element->password = malloc(strlen(pass)+1);
// sprintf(element->password,"%s", pass);
strcpy(element->password,pass);
或者写...
element->password = strdup(pass);
在 pass
的内容被复制到该空间之前,保留足够的空间来保存 pass
的内容。
关于c - 在 sprintf 中使用节点元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54508629/