[英]How to use malloc when calling strcat()?
我正在编写一个小程序来从文件中复制文本信息,编辑并将其保存到另一个文件中。 当我尝试执行指令时
a=fputs( strcat( "\"", strcat(string, "\",\n")), novo_arquivo);
它给了我分段错误核心转储错误。 研究了一下,发现必须使用malloc来分配memory,但是不知道这段代码应该怎么写。
将strcat()
与动态 memory 一起使用的粗略示例可能如下所示:
#include <stdio.h> // for printf
#include <string.h> // for strcat
#include <stdlib.h> // for calloc
int main()
{
char* novo_arquivo = "example_string";
// size + 3 to account for two quotes and a null terminator
char* concat_string = calloc(strlen(novo_arquivo) + 3, sizeof(*concat_string));
strcat(concat_string, "\"");
strcat(concat_string, novo_arquivo);
strcat(concat_string, "\"");
// write concat_string to a file...
printf("%s", concat_string);
free(concat_string);
}
您在堆而不是堆栈上声明concat_string
,因此您需要在使用完毕后释放它,否则您将创建 memory 泄漏。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.