con*_*com 2 c memory-leaks memory-management
我正在尝试在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上的Process Manager)观察内存使用情况时,似乎RAM很快被吃掉,并且当程序停止时它不可用执行.
这是内存泄漏吗?如果是这样,我做错了什么?是不是free(new_str)应该释放内存?
谢谢你的帮助.
编辑1:由PaulR发现的一个错误修复.问题仍然存在.
看起来RAM很快被吃掉了,当程序停止执行时它就不可用了.
你在看哪种RAM使用方法?系统中的总RAM使用量?
如果是这样,你所看到的可能是终端使用的内存 - 程序打印出来的每个字符都将由终端存储在RAM中(尽管它可能会开始在某个限制内丢弃内容).再试一次,但这一次,阻止输出显示在终端:
./program > /dev/null
作为一般规则,无论您有多少内存泄漏,它都会在程序终止时自动释放.我无法发现您程序中的任何泄漏.