简体   繁体   English

C在动态2D char数组中插入字符串or(char *),分段错误

[英]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. 因此,我需要编写一个需要从某些子进程中填充的二维char数组。 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. 我制作了一个程序,该程序对于插入的前三个字符串(或char* )非常有效,但是之后出现了分段错误错误。 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 我只是不知道怎么了

You lost result of your reallocation and next time you try to use old pointer to output . 您丢失了重新分配的结果,并且下次尝试使用旧指针进行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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM