MST
星途 面试题库

面试题:C语言中结构体指针数组free内存的基础问题

假设有如下结构体定义: ```c struct Student { char name[20]; int age; }; ``` 然后定义了一个结构体指针数组并分配了内存: ```c 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)); } ``` 请编写代码正确释放 `students` 数组及其每个元素所占用的内存,并说明这样做的原因。
16.3万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#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;
}

原因:

  1. 首先遍历 students 数组,使用 free(students[i]) 释放每个 students[i] 指向的 struct Student 结构体所占用的内存。因为每个 students[i] 都是通过 malloc 分配的内存,所以需要使用 free 释放,否则会造成内存泄漏。
  2. 然后使用 free(students) 释放 students 数组本身所占用的内存。students 是通过 malloc 分配的,同样需要 free 释放,以避免内存泄漏。