gpt4 book ai didi

c - Valgrind 在 C 中设置空字节错误

转载 作者:行者123 更新时间:2023-11-30 16:36:27 25 4
gpt4 key购买 nike

int length = strlen(input_str);
output_s = malloc((sizeof(char*) * totalSentences) + 1);
for (int i = 0; i < totalSentences; i++) {
output_s[i] = malloc((sizeof(char) * sentences[i]) + 1);
}

free(sentences);

currentSentence = 0;
int currentCharacter = 0;
int firstChar = 1;
for (int i = 0; i < length; i++) {

if (isalpha(*input_str) && (firstChar == 1)) {
output_s[currentSentence][currentCharacter] = (char)toupper(*input_str);
currentCharacter++;
firstChar = 0;
} else if (isalpha(*input_str)) {
output_s[currentSentence][currentCharacter] = (char)tolower(*input_str);
currentCharacter++;
} else if (!isspace(*input_str) && !ispunct(*input_str)) {
output_s[currentSentence][currentCharacter] = *input_str;
currentCharacter++;
}

if (isspace(*input_str)) {
firstChar = 1;
}

if (ispunct(*input_str)) {
firstChar = 1;
currentCharacter = 0;
currentSentence++;
input_str++;
if (currentSentence == totalSentences) {
break;
}
continue;
}

input_str++;
}

output_s[totalSentences] = NULL;

所以我在c中创建一个字符串数组,并使用for循环和printf我知道字符串被创建有效并且它在最后打印(null)所以我假设我正确设置了NULL字节以output_s[totalSentences] = NULL结束;然而,当通过 valgrind 运行它时,它显示

==18908== Invalid write of size 8
==18908== at 0x400BB1: camel_caser (camelCaser.c:99)
==18908== by 0x400D45: test_camelCaser (camelCaser_tests.c:34)
==18908== by 0x400E17: main (camelCaser_main.c:13)
==18908== Address 0x5204538 is 24 bytes inside a block of size 25 alloc'd
==18908== at 0x4C2DB8F: malloc (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so)
==18908== by 0x40090C: camel_caser (camelCaser.c:57)
==18908== by 0x400D45: test_camelCaser (camelCaser_tests.c:34)
==18908== by 0x400E17: main (camelCaser_main.c:13)

第 57 行是我对 malloc(sizeof(char*) * TotalSentences + 1) 进行 malloc 的行,第 99 行是我实际将数组中的最后一个字节设置为 NULL 的行,所以我不知道这是否以某种方式弄乱了数组中较早的内存,从而导致 null 被写入错误的位置,或者我是否没有分配足够的内存来容纳 NULL?

最佳答案

你绝对需要它是 output_s = malloc(sizeof(char*) * (totalSentences + 1)); 而不是 output_s = malloc((sizeof(char*) * TotalSentences ) + 1);.

代码 - 正如您所拥有的 - 为 TotalSentences char *s 分配空间,再加上 1 个字节。您的代码需要totalSentences + 1 char *s 的空间。这就是为什么 valgrind 会给出错误,指出您正在将 8 个字节写入分配的 25 个字节的 24 个字节的空间中。

关于c - Valgrind 在 C 中设置空字节错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48485241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com