c - C 中的内存分段失败

标签 c

我刚刚练习 C 语言,编写一些简单的 I/O 应用程序。测试运行(构建和运行)没有任何错误或警告,但实际的应用程序(以及调试器)正在泄漏内存。
我简化了应用程序,因此现在只有函数在泄漏内存。

char *new_name(char *old_name, char *operation)
{
    char file_num[2];

    char *edited_name = ( char* ) malloc( strlen( old_name ) + strlen( operation ) );
    strcat( edited_name, old_name );
    strcat( edited_name, operation );

    // Iterate through names of new file to see which doesn't exist
    int fnum = 1;
    char *tempname = ( char* ) malloc( strlen( old_name ) + strlen( operation ) + sizeof( file_num ) + sizeof( ".txt" ) );
    do
    {
        strcpy( tempname, edited_name );
        sprintf( file_num, "%d", fnum++ );
        strcat( tempname, file_num );
        strcat( tempname, ".txt" );
    } while ( file_exists( tempname ) );
    free(edited_name);

    return tempname;
}

int main()
{

    char *old_name = "textfile";
    char *operation = "_join";
    char *out_name = new_name(old_name, operation);

    printf( "%s", out_name );

    return 0;
}

我还尝试通过计算字符来将 malloc() “公式”更改为 int 值,但它似乎对我不起作用(我仍然相信问题存在,但我无法解决它)。

附注file_exists 非常简单,只返回一个 int

最佳答案

当然是内存泄漏了。 有两个 malloc,但只有一个 free

在离开 main 之前以及最后一次使用之后,您必须释放 out_name

关于c - C 中的内存分段失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53345485/

相关文章:

c - 为什么 memcpy() 更快?

c - 使用 realloc 收缩矩阵

c - 使用结构的成员变量之一分配结构内数组的长度是否可行?

C90 编译器提示没有原型(prototype)函数警告

c - 在 C 中子方法内使用循环的奇怪结果

python - 你如何将 Python cv2.cv.LoadImage 编码到 C IplImage->imageData 结构中

c - 为什么我的回答总是错

用 C 创建第二个进程

ios - 在 XCode/iOS 中实现 C 代码

函数在公共(public) API 中采用 void* 并在后台键入 * 时出现类型冲突错误