Search code examples
cdynamic-memory-allocationundefined-behaviorc-stringsstrcat

Segmentation fault when trying to concatenate an element of a 2d array


I wanted to use strcat() to concatenate an element of an array of strings. I tried:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    char **str = malloc(sizeof(char *) * 3);

    for (int i = 0; i < 3; i++) {
        str[i] = malloc(sizeof(char) * 8);
    }

    str[0] = "foo";
    str[1] = "bar";

    strcat(str[0], "H");

    for (int i = 0; i < 3; i++) {
        printf("%s\n", str[i]);
    }

    free(str);

    return 0;
}

and I get the error:

Segmentation fault (core dumped)

What should I do to get it right?


Solution

  • For starters the program has memory leaks. At first memory was allocated and its addresses were stored in pointers str[i]

    for (int i = 0; i < 3; i++) {
        str[i] = malloc(sizeof(char) * 8);
    }
    

    and then the pointers str[0] and str[1] were reassigned by addresses of string literals.

    str[0] = "foo";
    str[1] = "bar";
    

    As a result you may not change a string literal by this statement

    strcat(str[0], "H");
    

    because this invokes undefined behavior

    You have to write

    strcpy( str[0], "foo" );
    strcpy( str[1], "bar" );
    

    And this loop

    for (int i = 0; i < 3; i++) {
        printf("%s\n", str[i]);
    }
    

    also invokes undefined behavior because the element str[2] was not initialized by a string.

    Either you need to change the condition or the loop like i < 2 or to initialize the element str[2].

    And you need to free all the allocated memory like

    for (int i = 0; i < 3; i++) {
        free( str[i] );
    }
    
    free( str );