MST
星途 面试题库

面试题:C语言结构体指针数组内存释放的边界与优化问题

假设存在这样的结构体嵌套定义: ```c struct Inner { int data[100]; }; struct Outer { struct Inner *inner; struct Outer *next; }; ``` 通过如下方式创建了一个结构体指针数组并进行了一些复杂的嵌套和链接操作: ```c struct Outer **outers = (struct Outer **)malloc(10 * sizeof(struct Outer *)); for (int i = 0; i < 10; i++) { outers[i] = (struct Outer *)malloc(sizeof(struct Outer)); outers[i]->inner = (struct Inner *)malloc(sizeof(struct Inner)); if (i < 9) { outers[i]->next = outers[i + 1]; } else { outers[i]->next = NULL; } } ``` 现在要求编写一个函数 `safeFreeOuters` 来安全释放 `outers` 数组及其嵌套的所有内存,同时要考虑内存分配失败的情况(比如在 `malloc` 时返回 `NULL`),并对代码进行性能优化,尽量减少不必要的内存访问和指针操作。
40.1万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试
#include <stdio.h>
#include <stdlib.h>

struct Inner {
    int data[100];
};

struct Outer {
    struct Inner *inner;
    struct Outer *next;
};

void safeFreeOuters(struct Outer **outers, int count) {
    for (int i = 0; i < count; i++) {
        struct Outer *current = outers[i];
        while (current != NULL) {
            struct Outer *next = current->next;
            if (current->inner != NULL) {
                free(current->inner);
            }
            free(current);
            current = next;
        }
    }
    free(outers);
}