【发布时间】:2018-07-07 04:52:17
【问题描述】:
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) 的行,第 99 行是我实际将数组中的最后一个字节设置为 NULL 的行,所以我不知道这是否以某种方式弄乱了数组中较早的内存,导致 null 被写入了一个不好的位置,还是我没有分配足够的内存来容纳 NULL?
【问题讨论】:
-
第一个
malloc()中的乘法和加法可能是错误的括号。奇数字节在指针数组中没有用。你可能想要'(length + 1) * sizeof(char *)`。 -
什么是
sentences[i]? -
在确定句子总数后,我制作了一个数组句子,跟踪每个句子的字符数,以便我可以制作一个适当大小的数组来包含它们