首页 > 解决方案 > C中的内存分段失败

问题描述

我只是在练习 C,编写一些简单的 I/O 应用程序。测试运行 (Build&Run) 没有任何错误或警告,但实际的应用程序(以及调试器)正在泄漏内存。
我简化了应用程序,所以它现在只是泄漏内存的功能。

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 值,但这似乎对我不起作用(我仍然相信问题存在,但我无法解决它)。

PSfile_exists非常简单,只返回一个int

标签: c

解决方案


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

您必须freeout_name离开 main 之前和最后一次使用它之后。


推荐阅读