У меня есть указатель на структуру, а один из объектов в структуре - int **. Двойной указатель используется для динамического выделения памяти для 2d-массива. Мне трудно понять, как освободить память для этого массива. Есть идеи?Свободная динамически распределенная память из 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 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;
}
[Не отвергни таНос] (http://stackoverflow.com/questions/605845/ do-i-cast-the-result-of-malloc) – Barmar
Какие идеи? вы делаете это правильно. Просто удалите бросок из malloc. Кроме того, 'printf (« Out of memory \ n »);' недостаточно, вы откладываете прерывание, а не dereferene указатель. –
Вы освобождаете его правильно. Но вы не распределяете его правильно. 'getTime' возвращает адрес локальной переменной, что недопустимо. – Barmar