我刚刚练习 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/