gpt4 book ai didi

c - 在 C 程序中使用 free 时的奇怪行为

转载 作者:行者123 更新时间:2023-11-30 17:25:10 24 4
gpt4 key购买 nike

我有一些程序可以解压缩此处已经提到的一些字符串:How to decompres array of char in c 。完成后,我遇到了 free 函数的问题(没有它,它可以正常工作)。有一些奇怪的行为,最后一个断言失败,因为: Aborted;核心转储;

当我调试这个程序时,我发现问题出在这个循环中:

    for (j = 0; j < max - 1; j++) {
vysledek[index] = src[i - pom];
printf("cccc%d\n%s\n", j,vysledek);

printf("xxx%c", src[i - pom]);
index++;
}

它打印:

...
xxx#cccc19
HHeeeeeellllllllooooooooooooooo#####################�
xxx#cccc20
HHeeeeeellllllllooooooooooooooo######################
xxx#cccc21
HHeeeeeellllllllooooooooooooooo#######################
xxx#cccc22
HHeeeeeellllllllooooooooooooooo########################
xxx#cccc23
HHeeeeeellllllllooooooooooooooo#########################Hello______________________________world!
xxx#cccc24
HHeeeeeellllllllooooooooooooooo##########################ello______________________________world!
...

有人能给我解释一下吗?第二个断言中的 Hello world 如何在第三个断言中发现?

整个程序在这里:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <assert.h>

char * decompress(const char * src) {

int max = 0;
int pom = 1;
int maxSize = 0;
int index = 0;
int isNumber = 0;

int i;
for (i = 0; src[i] != 0; i++) {
max = 0;
isNumber = 0;
while (isdigit(src[i])) {
int digit = (src[i] - '0');
max = max * 10 + digit;
i++;
isNumber = 1;
}
if (max == 0 && !isNumber) {
max = 1;
}

maxSize = maxSize + max;
}

char *vysledek = (char*) malloc((maxSize) * sizeof (int));

for (i = 0; src[i] != 0; i++) {
max = 0;
pom = 0;
isNumber = 0;
while (isdigit(src[i])) {
int digit = (src[i] - '0');
max = max * 10 + digit;
i++;
pom++;
isNumber = 1;
}

if (!isNumber) {
vysledek[index] = src[i];
//printf("%c", src[i]);
index++;
} else {
i--;
int j;

if (max < 1) {
index--;
}


for (j = 0; j < max - 1; j++) {
vysledek[index] = src[i - pom];
//printf("cccc%d\n%s\n", j,vysledek);

//printf("xxx%c", src[i - pom]);
index++;
}
}
//printf("\n%d\n", index);

}

return vysledek;
}

int main(int argc, char * argv []) {

char * res;

assert(!strcmp(
(res = decompress("Hello world!")),
"Hello world!"));
//free(res);

assert(!strcmp(
(res = decompress("Hello_30world!")),
"Hello______________________________world!"));
//free(res);

assert(!strcmp(
(res = decompress("H2e6l8o15 35w5o6r-2d0!!")),
"HHeeeeeellllllllooooooooooooooo wwwwwoooooor--!!"));

//free(res);
return 0;
}

最佳答案

问题是,您将空终止字符串与非空终止字符串进行比较。在函数 decompress() 中,您需要再保留一个 int 并将缺少的\0 添加到复制的缓冲区中。

char *vysledek = (char*) malloc((maxSize) * sizeof (int) + sizeof(int));
[...]
vysledek[index] = '\0';

关于c - 在 C 程序中使用 free 时的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27103712/

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