Search code examples
cmallocstrcat

How to use malloc when calling strcat()?


I'm coding a small program to copy text information from a file, edit and save it to another one. When I try to execute the instruction

a=fputs( strcat( "\"", strcat(string, "\",\n")), novo_arquivo);

it gives me the segmentation fault core dumped error. Researching, I found out that I must use malloc to allocate memory, but I don't know how this code should be written.


Solution

  • A rough example of using strcat() with dynamic memory might look something like this:

    #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);
    }
    

    You're declaring concat_string on the heap instead of the stack, so you'll need to free it when you're finished using it, or you'll create a memory leak.