c - 我的 C 程序中函数返回局部变量错误的地址

标签 c compiler-errors

我的编译器出现了标题中提到的错误。我不明白我做错了什么。有人可以向我解释一下吗?我已经有一段时间没有和 C 一起工作了。

char** answer(char c)
{

// Initial scanf and check
    printf("Please input the character which you want to build your diamond with");
    if (check(c) == true) {
        printf("\n");
    } else {
        printf("Not a valid character");
        return NULL; 
    }


//--------------------------------------------------------------------------------------------------------
//Preprocessing
//--------------------------------------------------------------------------------------------------------

//processing declarations

//Number of Rows
int pre_r = (int)c - 65;
int r = ( pre_r * 2 ) + 1; 

//Declare the column of pointers
char *diamond[r];

//Declare the rwo of characters 
// 2D array declared here to save on computation in situations where characters are not valid 
for (int i=0; i<r; i++)
     diamond[i] = (char*)malloc(c * sizeof(char));

//--------------------------------------------------------------------------------------------------------
//Postprocessing 
//--------------------------------------------------------------------------------------------------------

return diamond;
free(diamond);  
}

最佳答案

您有两个问题:

  1. 您无法返回函数本地变量的地址,因为它是在函数的堆栈帧中分配的,因此当函数返回时,它会与函数本身一起释放。

  2. 你使用free()是错误的,只有当你使用过malloc()时才应该使用free(),甚至不能使用已进行算术运算的指针,而只能使用由 malloc()/calloc()/realloc() 之一返回的指针。并且仅当您不再需要使用数据时,或者当您不再取消引用指针时更好。

试试这个,希望上面的解释+这段代码能帮助你理解

char **
answer(char columns)
{
    int rows;
    char **diamond;

    printf("Please input the character which you want to build your diamond with");
    if (check(columns) == true) {
        printf("\n");
    } else {
        printf("Not a valid character");
        return NULL;
    }
    rows = 2 * (columns - 'A') + 1;
    diamond = malloc(rows * sizeof(*diamond));
    if (diamond == NULL)
        return NULL;
    /* You must check for `NULL' for every `malloc()' */
    for (int i = 0 ; i < rows ; i++)
        diamond[i] = malloc(columns + 1); /* <- check for `NULL' */
    /*                                ^
     * if this is for a string you need space for the `nul' terminator
     */
    return diamond;
}

此外,请使用有意义的变量名称,并且不要忘记为该代码中的每个 malloc() 调用 free(),这由您决定。我相信你能弄清楚如何。

关于c - 我的 C 程序中函数返回局部变量错误的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32899796/

相关文章:

swift - case 语句中 Unresolved 标识符错误

c++ - 这个错误是什么意思“表达式必须有指向类的指针类型”?

intellij-idea - 无法在Kotlin中转换为收藏

java - Android Studio Flamingo 出现“compileDebugJavaWithJavac”错误

c - 产生键盘事件击键

c - FMOD 播放重叠声音

c - 函数调用后指针未指向正确的数组元素

c - 在 C 中使用 "for"循环的迭代变量时出现奇怪的输出

c - 将结构地址从 C 传递到 Lua 并在 Lua 中访问其内容而无需复制数据

java - “Cannot find symbol”或 “Cannot resolve symbol”错误是什么意思?