Cnoffel Cnoffel - 13 days ago 9
C Question

C insert a string or(char*) in a dynamic 2D char array, Segmentation fault

So I need to program a 2-dimensional

char
array that needs to get filled from some Child Processes. I don't know how many lines will be returned at run-time.

I made a program that works well for the first three strings (or
char*
) inserted, but after that I get segmentation fault errors. The array should keep the values/strings it has in it. Here's the code:

Global row count:

static int rows = 1;


Array initialisation:

char **output = (char **)malloc(sizeof(char*) * 1);
output[0] = (char *)malloc(sizeof(char) * 1023);
output[0][0] = '#';


Adding:

char foo[1023];
insertArray(output, "bbb");
insertArray(output, foo);
insertArray(output, "bbb");
insertArray(output, "bbb");


It actually works fine the first 3 times

Function:

static void insertArray(char **c, char *itemToInsert) {

if (c[0][0] == '#') {
strncpy(c[0], itemToInsert, 1023);
}
else {

c = (char **)realloc(c, (rows + 1) * sizeof(char*));
for (int i = 0; i < rows+1; i++) {
c[i] = realloc(c[i],sizeof(char) * 1024);
}
strcpy(c[rows], itemToInsert);
rows++;
}

}


I just can't figure out whats wrong

Answer

You lost result of your reallocation and next time you try to use old pointer to output.

You can redesign like this:

output = insertArray(output, ...);
output = insertArray(output, ...);
output = insertArray(output, ...);
...

static char **insertArray(char **c, char const *itemToInsert)
{
    ...
    return c;
}