C语言 从结构内的 2D 数组释放动态分配的内存



我有一个指向结构体的指针,结构中的一个对象是int **。双指针用于为 2D 数组动态分配内存。我在弄清楚如何释放此数组的内存时遇到问题。有什么想法吗?

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 memoryn");
    for(i=0; i<rows; i++) {
        time.date[i] = (int *)malloc(cols*sizeof(int));
        if(time.date[i] == NULL)
            printf("Out of memoryn");
    }
    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 memoryn");
    for(i=0; i<rows; i++) {
        time->date[i] = (int *)malloc(cols*sizeof(int));
        if(time->date[i] == NULL)
            printf("Out of memoryn");
    }
    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

最新更新