MST

星途 面试题库

面试题:C语言结构体指针专家难度题

在一个复杂的C项目中,有多个结构体嵌套且存在结构体指针的情况,如struct A { struct B *b_ptr; int a_value; }; struct B { struct C *c_ptr; int b_value; }; struct C { int c_value; }; 现要对这些结构体进行内存管理,防止内存泄漏,并且在结构体间传递数据时保证数据的一致性和安全性,设计一个通用的内存管理和数据传递方案,并编写关键代码片段。
50.2万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试

内存管理方案

  1. 内存分配:使用 malloc 系列函数为结构体分配内存。
  2. 内存释放:按照结构体嵌套关系,从内层到外层依次释放内存,避免内存泄漏。

数据传递方案

  1. 初始化:在分配内存后,对结构体成员进行初始化,确保数据一致性。
  2. 传递:通过结构体指针传递数据时,确保指针指向有效的内存地址,保证数据安全性。

关键代码片段

#include <stdio.h>
#include <stdlib.h>

// 定义结构体
struct C {
    int c_value;
};

struct B {
    struct C *c_ptr;
    int b_value;
};

struct A {
    struct B *b_ptr;
    int a_value;
};

// 分配内存并初始化
struct A* create_A() {
    struct A *a = (struct A*)malloc(sizeof(struct A));
    if (a == NULL) {
        return NULL;
    }
    a->a_value = 0;

    struct B *b = (struct B*)malloc(sizeof(struct B));
    if (b == NULL) {
        free(a);
        return NULL;
    }
    b->b_value = 0;

    struct C *c = (struct C*)malloc(sizeof(struct C));
    if (c == NULL) {
        free(b);
        free(a);
        return NULL;
    }
    c->c_value = 0;

    b->c_ptr = c;
    a->b_ptr = b;

    return a;
}

// 释放内存
void free_A(struct A *a) {
    if (a != NULL) {
        if (a->b_ptr != NULL) {
            if (a->b_ptr->c_ptr != NULL) {
                free(a->b_ptr->c_ptr);
            }
            free(a->b_ptr);
        }
        free(a);
    }
}

int main() {
    struct A *a = create_A();
    if (a != NULL) {
        // 使用结构体a
        a->a_value = 1;
        a->b_ptr->b_value = 2;
        a->b_ptr->c_ptr->c_value = 3;

        // 释放内存
        free_A(a);
    }
    return 0;
}

代码说明

  1. create_A 函数:负责为 struct Astruct Bstruct C 分配内存,并初始化成员变量。如果任何一步内存分配失败,会按照顺序释放之前分配的内存。
  2. free_A 函数:按照结构体嵌套的反向顺序,从内层到外层释放内存,防止内存泄漏。
  3. main 函数:调用 create_A 函数创建结构体实例并使用,最后调用 free_A 函数释放内存。