c - 从结构中的二维数组中释放动态分配的内存

标签 c pointers struct malloc multidimensional-array

我有一个指向结构的指针,结构中的对象之一是一个 int **。双指针用于为二维数组动态分配内存。我无法弄清楚如何释放该数组的内存。有什么想法吗?

struct time_data {
    int *week;
    int *sec;
    int **date;
};
typedef struct time_data time_data;

time_data *getTime(time_data *timeptr, int rows, int cols) {
    int i = 0;
    time_data time;

    // allocate memory for time.date field
    time.date = (int **)malloc(rows*(sizeof(int *))); // allocate rows
    if(time.date == NULL)
        printf("Out of memory\n");
    for(i=0; i<rows; i++) {
        time.date[i] = (int *)malloc(cols*sizeof(int));
        if(time.date[i] == NULL)
            printf("Out of memory\n");
    }
    timeptr = &time;
    return timeptr;
}

int main(int argc, const char * argv[]) {
    time_data *time = NULL;
    int rows = 43200, cols = 6;
    int i;
    time = getTime(time, rows, cols);

    for(i=0; i<rows; i++)
        free(time->date[i]); // problem here
    free(time->date);

}

修改版本(以防其他人有类似问题)

    struct time_data {
    int *week;
    int *sec;
    int **date;
};
typedef struct time_data time_data;

time_data *getTime(int rows, int cols) {
    int i = 0;
    time_data *time = malloc(sizeof(*time));

    // allocate memory for time.date field
    time->date = (int **)malloc(rows*(sizeof(int *))); // allocate rows
    if(time->date == NULL)
        printf("Out of memory\n");

    for(i=0; i<rows; i++) {
        time->date[i] = (int *)malloc(cols*sizeof(int));
        if(time->date[i] == NULL)
            printf("Out of memory\n");
    }
    return time;
}

int main(int argc, const char * argv[]) {
    time_data *time = NULL;
    int rows = 43200, cols = 6;
    int i;
    time = getTime(rows, cols);

    for(i=0; i<rows; i++)
        free(time->date[i]); // problem here
    free(time->date);
return 0;
}

最佳答案

你的释放没问题,但是你有一个严重的错误

timeptr = &time;
return timeptr;

您正在返回局部变量的地址。

局部变量分配在函数的栈帧中,一旦函数返回,数据将不复存在。

你也应该为此使用 malloc

timeptr = malloc(sizeof(*timeptr));

而且您还必须从 main()

返回一个 int

关于c - 从结构中的二维数组中释放动态分配的内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28205889/

相关文章:

使用其他文件夹中的对象在 gcc 中动态编译

c++ - 类继承链和指向每个类的指针

c++ - 为什么在 C++ 中返回指向堆上变量的指针而不是变量本身

c++ - 我被这段使用指针访问二维数组中的值的代码所困扰

c++ - 虽然循环效率低下且无法正常工作

c - 打印结构体的值不显示正确的值

c - 这个简单的 C 程序的输出

c++ - 如何在 SQLite3 中查找 stmt 到行号?

C代码编码器! (数组)(嵌套循环)(fgets)(语法?)

struct - 在 Julia 中以编程方式定义结构