面试题答案
一键面试#include <stdio.h>
#include <stdlib.h>
int main() {
struct Student {
char name[20];
int age;
};
struct Student **students = (struct Student **)malloc(5 * sizeof(struct Student *));
for (int i = 0; i < 5; i++) {
students[i] = (struct Student *)malloc(sizeof(struct Student));
}
// 释放内存
for (int i = 0; i < 5; i++) {
free(students[i]);
}
free(students);
return 0;
}
原因:
- 首先遍历
students
数组,使用free(students[i])
释放每个students[i]
指向的struct Student
结构体所占用的内存。因为每个students[i]
都是通过malloc
分配的内存,所以需要使用free
释放,否则会造成内存泄漏。 - 然后使用
free(students)
释放students
数组本身所占用的内存。students
是通过malloc
分配的,同样需要free
释放,以避免内存泄漏。