簡體   English   中英

調用strcat()時如何使用malloc?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM