调用strcat()时如何使用malloc?
How to use malloc when calling strcat()?
我正在编写一个小程序来从一个文件中复制文本信息,编辑并保存到另一个文件中。当我尝试执行指令时
a=fputs( strcat( "\"", strcat(string, "\",\n")), novo_arquivo);
它给了我 segmentation fault core dumped 错误。研究了一下,发现必须要用malloc来分配内存,但是不知道这段代码应该怎么写
使用 strcat()
和动态内存的粗略示例可能如下所示:
#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
,因此您需要在使用完后释放它,否则会造成内存泄漏。
我正在编写一个小程序来从一个文件中复制文本信息,编辑并保存到另一个文件中。当我尝试执行指令时
a=fputs( strcat( "\"", strcat(string, "\",\n")), novo_arquivo);
它给了我 segmentation fault core dumped 错误。研究了一下,发现必须要用malloc来分配内存,但是不知道这段代码应该怎么写
使用 strcat()
和动态内存的粗略示例可能如下所示:
#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
,因此您需要在使用完后释放它,否则会造成内存泄漏。