从文本文件中读入单词并将错误存储到C中的动态数组中
我正在尝试使用fscanf从C中的文本文件中读取单词,并将它们放入动态分配的数组中。然而,我在Valgrind中不断得到错误,并且(null)字符似乎在我的输出中出现。我创建了一个双指针**str_数组来容纳每个字符数组,并最初为4个字符数组分配足够的空间。fscanf运行读入字符串并将其存储到str[]中,我使用strcpy将str[]的字符串复制到str_数组中。如果str_数组需要容纳更多字符串,我会重新分配内存从文本文件中读入单词并将错误存储到C中的动态数组中,c,arrays,string,valgrind,C,Arrays,String,Valgrind,我正在尝试使用fscanf从C中的文本文件中读取单词,并将它们放入动态分配的数组中。然而,我在Valgrind中不断得到错误,并且(null)字符似乎在我的输出中出现。我创建了一个双指针**str_数组来容纳每个字符数组,并最初为4个字符数组分配足够的空间。fscanf运行读入字符串并将其存储到str[]中,我使用strcpy将str[]的字符串复制到str_数组中。如果str_数组需要容纳更多字符串,我会重新分配内存 #include <stdlib.h> #include <
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[]) {
char str[80];
int word_alloc = 0;
int word_count = 0;
char **str_array;
FILE *file;
file = fopen(argv[1], "r");
// Allocate memory to the array of strings (char arrays)
word_alloc = 4;
str_array = (char **) malloc(sizeof(char*) * word_alloc);
while (fscanf(file, "%s", str) != EOF) {
// If there are more than 4 strings, double size
if (word_count > word_alloc) {
word_alloc *= 2;
str_array = (char **) realloc(str_array, sizeof(char*) * word_alloc);
}
str_array[word_count] = (char *) malloc(sizeof(char) * (strlen(str) + 1));
strcpy(str_array[word_count], str);
++word_count;
}
int i = 0;
for (; i<word_count; i++) {
printf("Word: %s\n", str_array[i]);
}
i = 0;
for (; i<word_count; i++) {
free(str_array[word_count]);
}
free(str_array);
fclose(file);
return 0;
}
free
循环中出现错误:
i = 0;
for (; i<word_count; i++) {
free(str_array[word_count]);
}
i=0;
对于(;i您在free
循环中有一个错误:
i = 0;
for (; i<word_count; i++) {
free(str_array[word_count]);
}
i=0;
对于(;i“%s”
在scanf中应该是“%79s”
。当word\u count==word\u alloc
时,也可以写越界。使用calloc
分配(或将新内存初始化为NULL)以消除条件跳转或移动取决于未初始化的值
…和..不要抛出malloc的返回值
…大小为8的无效写入是因为当word\u count>=word\u alloc(不仅仅是>)时需要realloc,因为C数组是基于零的。您存储单词0、1、2、3(即4个单词指针,所有您已分配!),因此当word\u count=4时,您必须在写入位置[4]之前进行realloc在目标中。“%s”
应该是scanf中的“%79s”
。当word\u count==word\u alloc
时,也可以写越界。使用calloc
分配(或将新内存初始化为NULL)以消除条件跳转或移动取决于未初始化的值
…和..不要抛出malloc的返回值
…大小为8的无效写入是因为当word\u count>=word\u alloc(不仅仅是>)时需要realloc,因为C数组是基于零的。您存储单词0、1、2、3(即4个单词指针,所有您已分配!),因此当word\u count=4时,您必须在写入位置[4]之前进行realloc在目的地。