c - 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。
解决方案
当然是内存泄漏。有两个malloc
,但只有一个free
。
您必须free
在out_name
离开 main 之前和最后一次使用它之后。
推荐阅读
- c - 无需 malloc 和 calloc 动态分配数组
- excel - 如何在excel中对一个单词进行子串并添加一个字母并转换为大写
- python - 如何在 Keras Tensorflow 中为采样创建自定义层?
- google-app-engine - Google Cloud SQL 实例的连接选项卡永远加载控制台界面
- java - Java.text.ParseException:无法解析的日期
- unity3d - 从服务器获取 AssetBundle 清单文件
- php - 如何从 2 个 URL 请求中一次性组合 2 个 json 响应
- elasticsearch - Vega 和 Kibana - 动态时间戳标签和过滤查询
- flutter - 如何使用 flutter_webview_plugin 播放视频
- r - R问题中的整数64到数据时间转换?