函数返回的自由数组

Free array returned from function

抱歉,如果这出现在其他地方,我无法找到明确的答案。 我一直在使用 Ed S 的答案,选项 1(链接如下)来分配内存,填充数组,然后 return 将其返回给调用者。 他建议您在完成后释放内存,但是当我添加 free() 行时,我得到了一个核心转储。 我对 GDB 有所了解,但我的技能可能不是必需的。

在此先感谢您提供的任何帮助。

Link 回答:Returning an array using C

代码:

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

char * createArray();

int main(int argc, char *argv[]){
    printf("Creating Array...\n");
    // pointer to an int
    char *p;
    // size of the array
    int i,j;
    // width of array
    int width = 7;
    // height of array
    int height = 5;
    // get an array from the function
    p = createArray(width, height);
    // check if p was created properly
    if (p){
        // print out the array
        for (i = 0; i < width; ++i){
            for (j = 0; j < height; ++j){
                printf("[%c] ", *(p + (i * width) + j)); 
            }
        printf("\n");
        }

        // here's where it hits the fan
        free(p);
    }
    return 0;
}

char * createArray(int w, int h){
    // allocate some memory for the array
    char *r = malloc(w * h * sizeof(char));
    // check if the memory allocation was successful
    if(!r){
        return NULL;
    }
    int i, j;
    int count = 0;
    for (i = 0; i < w; ++i){
        for (j = 0; j < h; ++j){
            *(r + (i * w) + j) = 'X';
            ++count;
        }
    }
    return r;
}

有了这个

char *r = malloc(w * h * sizeof(char));

您分配 w * h(7 * 5 = 35 字节)内存。但是

        *(r + (i * w) + j) = 'X';

可以访问超出您分配的 35 个字节(您将看到是否在循环中测试 i * w + j 的可能值),导致未定义的行为。

这可能会覆盖 malloc 的内部数据结构,因此您在 free() 时碰巧会得到核心转储。

你在这些行上犯了错误

*(r + (i * w) + j) = 'X';

printf("[%c] ", *(p + (i * width) + j));

为了保持在“2D”数组的边界内——它是一维的,但你像编译器一样处理它——它应该是 i * length

*(r + (i * h) + j) = 'X';`

printf("[%c] ", *(p + (i * height) + j)); `

如果你用这个,你应该可以在边界内而不至于弄得乱七八糟。