Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C Valgrind在二维数组中读取大小1无效_C_Memory Management_Size_Valgrind - Fatal编程技术网

C Valgrind在二维数组中读取大小1无效

C Valgrind在二维数组中读取大小1无效,c,memory-management,size,valgrind,C,Memory Management,Size,Valgrind,我对valgrind和C都是相当陌生的,在解释我的代码到底出了什么问题时遇到了困难。我在第285行得到一个无效的读取大小1,它表示在分配了一个5块之后,地址是0字节。我的分配如下: output = malloc(sizeof(char**)); output[0] = malloc(sizeof(char*)*size); for(i = 0; i < size; i++){ output[0][i] = malloc(wordLength); } output=malloc(

我对valgrind和C都是相当陌生的,在解释我的代码到底出了什么问题时遇到了困难。我在第285行得到一个无效的读取大小1,它表示在分配了一个5块之后,地址是0字节。我的分配如下:

output = malloc(sizeof(char**));
output[0] = malloc(sizeof(char*)*size);
for(i = 0; i < size; i++){
    output[0][i] = malloc(wordLength);
}
output=malloc(sizeof(char**));
输出[0]=malloc(sizeof(char*)*size);
对于(i=0;i
无效的读取大小和周围的行是:

for(j = 0; j < size; j++){
    printf("%s, ", output[0][j]);
    free(output[0][j]);
}
(j=0;j{ printf(“%s”,输出[0][j]); 自由(输出[0][j]); }
我不会在代码中的任何其他地方释放这些数据,所以我不确定哪里出了问题。此外,输出中实际上不止一个2d数组,但我认为没有必要深入讨论,因为这个错误似乎源于这个特定的情况。

这个数据结构中的单词放在哪里?
%s
指令将读取字符,直到它到达
\0
空终止符。因此,如果单词比分配的内存块长一个字符,printf行将读取超过末尾的一个字节。

输出[0]中是否只有一个无效读取大小警告或每个单词一个警告?每一个单词都有一个strncpy,第三个参数是wordLength,因此它应该只将wordLength字符放入每个块
wordLength
是否包含空终止符?如果不是,则strncopy将导致字符串不以null结尾。通过执行
output[0][j][wordLength-1]=0
尝试在
printf
之前强制空终止,看看valgrind读取错误是否消失。是的,我会尝试这样做,因为我使用strlen查找我认为不包括空终止符的wordLength。是的,这就是问题,我只需要在末尾添加一个空终止符。非常感谢。