在sprintf中使用节点元素

时间:2019-02-03 23:27:36

标签: c segmentation-fault printf

所以我一直在尝试使程序的这一部分读取特定文件,其中包含这种格式的名称和数字

  

姓名

等并将它们存储在结构列表中

to-report occurrences [#x #the-list]
  report reduce
    [ [occurrence-count next-item] -> ifelse-value (next-item = #x)
        [occurrence-count + 1] [occurrence-count] ] (fput 0 #the-list)
end

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

Valgrind显示:

struct list_element {
    char *password;
    int count;
    list_element* next;
};

任何有关我的错误发生的地方的技巧,我们都会感谢:)

1 个答案:

答案 0 :(得分:2)

对于list_element* element = malloc(sizeof(list_element));,您正在为list元素分配空间,但没有为成员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的内容。

相关问题