通过C中的函数更改动态2D字符数组?

时间:2014-04-26 21:10:55

标签: c arrays function dynamic segmentation-fault

我正在创建这个示例运行,这样我就可以更好地理解如何通过其他函数编辑动态数组,但是一旦我添加了辅助函数,我就开始运行segfaults了。

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

void other_side(char ***funk);

int main()
{
    int i;
    char *argv[11] = {"fish", "dish", "lags", "fags", "shag", "cool", "bean", "rekt", "noon", "coon", "lolz"};

    char **yep, **nop;
    yep = malloc(10 * sizeof *yep);
    if(!yep) { // <-----------------added check for malloc error
        printf("Error: failure to allocate memory\n");
        exit(1);
    }

    printf("10 times %lu\n\n", sizeof *yep);
    for(i = 0; i<10; i++) {
        yep[i] = strdup(argv[i]);
        printf("%s is in yep.\n", *(yep+i)); 
    }
    nop = realloc(yep, 11 * sizeof *yep); //you reallocate to the new total size.
    if(nop == NULL) {
        printf("Error: failure to allocate memory\n")
        exit(1);
    }
    yep = nop;
    *(yep+10) = strdup(argv[10]); 
    printf("Last but certainly not least, %s is in yep.\n", *(yep+10));

    printf("Now to send yep over to the other side and have its values changed.\n");

    other_side(&yep);

    printf("Did it change?\n\n");

    for(i=0; i<11; i++)
        printf("%s is in yep.\n", *(yep+i));

    for(i=0; i<11; i++) { //issue fixed when added strdup() above, previously static
        free(*(yep+i)); 
    }
    free(yep);
    return 0;
}

void other_side(char ***funk)
{
    char *arr[11] = {"dude","yeah","gnar","nice","epic","need","more", "word","four","this","test"};
    int i;
    for(i=0; i<11; i++) {
        **(funk+i) = strdup(arr[i]); //added strdup() here as well
        printf("%s is currently in yep.\n", **(funk+i));
    }
    printf("\n");
}

我注意到的一些事情是,当我尝试将第11块内存释放到main()中的数组时,Valgrind会注意到一个不必要的空闲。我不确定这是否是我的问题,但我也注意到该功能只会在导致分段错误之前更改两个单词。

编辑笔记:由于编辑我仍然得到段错误,但是valgrind已经对发生的事情更加清楚了。 (地址0x400B18处映射区域的权限不正确)

1 个答案:

答案 0 :(得分:0)

您对运营商的优先顺序非常重要,您错过了一对parens以确保正确完成。这个:**(funk+i)表示:*(funk[i]),而不是(*funk)[i]这就是你想要的。

此:

**(funk+i) = strdup(arr[i]);
printf("%s is currently in yep.\n", **(funk+i));

应该是这样的:

*((*funk)+i) = strdup(arr[i]);
printf("%s is currently in yep.\n", *((*funk)+i));

坦率地说,它更容易理解为:

(*funk)[i] = strdup(arr[i]);
printf("%s is currently in yep.\n", (*funk)[i]);

我将剩余的内存管理留给您修复。 (即,您在上述循环代码中覆盖的所有指针所指向的动态内存泄漏)。