我正在尝试在 C 中构建一个 str_replace 函数(以便学习 C)。为了让事情变得更简单,我决定创建两个辅助函数,其中一个具有以下原型:
char * str_shift_right(const char * string, char fill, int32_t n);
它接受一个字符串并将字符添加到给定字符串fill
的n
第 th 位置。这是完整的代码:
// replace the nth char with 'fill' in 'string', 0-indexed
char * str_shift_right(const char * string, char fill, int32_t n) {
// +1 the null byte, +1 for the new char
int32_t new_size = (int32_t) strlen(string) + 2;
char * new_string = NULL;
new_string = calloc(new_size, sizeof(char));
new_string[new_size - 1] = '\0';
int32_t i = 0;
while (i < strlen(string) + 1) {
// insert replacement char if on the right position
if (i == n) {
new_string[i] = fill;
// if the replacement has been done, shift remaining chars to the right
} else if (i > n) {
new_string[i] = string[i - 1];
// this is the begining of the new string, same as the old one
} else {
new_string[i] = string[i];
}
i++;
}
return new_string;
}
我想确保这个函数没有泄漏内存,所以我尝试执行以下代码:
int main(int argc, const char * argv[])
{
do {
char * new_str = str_shift_right("Hello world !", 'x', 4);
printf("%s", new_str);
free(new_str);
} while (1);
return 0;
}
但是,当使用活动监视器(Mac OSX 应用程序,对于那些不熟悉的人来说,有点像 Windows 上的进程管理器)查看内存使用情况时,似乎 RAM 很快被吃光了,并且在程序停止时它不可用执行。
这就是内存泄漏吗?如果是这样,我做错了什么?调用不free(new_str)
应该释放内存吗?
谢谢你的帮助。
编辑 1:由 PaulR 发现的一个错误修复。问题依然存在。