解决错误 'Address of stack memory associated with local variable returned'

Work around error 'Address of stack memory associated with local variable returned'

我正在尝试调用一个方法,该方法将生成一个 2D 字符数组(字符串数组)并且 return 它将在另一个函数中使用。

我的例子:

char ** example(void)
{
    char *test[3];

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

    test[foo][bar] = 'baz'; // of course I would declare 'foo' and 'bar'
    // ...
    // ...

    return test;
}

然后我希望能够按如下方式使用数组:

void otherMethod(void)
{
    char ** args = example();
    // do stuff with args
}

问题是这会产生 错误:

warning: address of stack memory associated with local variable 'test' returned [-Wreturn-stack-address]

我可以通过在全局范围内而不是在本地范围内定义 test 来解决这个问题,但我非常不愿意这样做,因为它看起来很乱,尤其是当我要拥有其中的几个时。

有没有办法在 C 语言中创建和 return 一个字符串数组而不用全局定义它?

你走在正确的轨道上。您需要做的就是将 test[3]; 本身的分配从自动(又名 "stack")更改为动态(又名 "heap"):

char **test = malloc(3 * sizeof(char*));

这使得从您的函数中 return test 合法,因为它不再是 returning 与堆栈分配关联的地址。

当然,调用者需要free return 内部的指针和return 本身。您可能需要考虑为此提供辅助函数。

另一种方法是将 char test[] 作为函数参数:

void example(char *test[], size_t count) {
    for (size_t i = 0 ; i < count ; i++) {
        test[i] = malloc(3 * sizeof(char));
    }
    ...
    // return is not required
}

现在调用者必须将一个合适大小的数组传递给您的函数,这样您就可以避免分配它。

使用malloc:

char ** example(void)
{
    char** test = malloc(sizeof(char*) * 3);

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

    test[foo][bar] = 'baz'; // of course I would declare 'foo' and 'bar'
    // ...
    // ...

    return test;
}

这主要是对@dasblinkenlight 回答的补充。

你写:

test[i] = malloc(3 * sizeof(char));

test[i] 现在是一个字符数组,它可以包含最多 2 个字符的字符串和终止空值。你应该这样加载它:

strncpy(test[i], 2, str); /* where str is another char pointer */

所以我会写:

test[i] = malloc(4 * sizeof(char));
strcpy(test[i], "baz");

C 字符串乍一看可能会造成混淆 ;-)

使用static:

static char *test[3];