MST

星途 面试题库

面试题:C语言结构体嵌套与动态内存管理

定义一个结构体表示公司部门,部门结构体包含部门名称(字符串),以及一个指向员工结构体数组的指针,员工结构体包含员工姓名(字符串)、职位(字符串)和薪资。编写代码实现动态分配内存来创建一个部门,并向该部门动态添加m个员工,同时要妥善处理内存的分配与释放,防止内存泄漏。请给出完整的代码实现,并分析可能出现内存泄漏的情况及如何避免。
40.0万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

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

// 定义员工结构体
typedef struct Employee {
    char name[50];
    char position[50];
    double salary;
} Employee;

// 定义部门结构体
typedef struct Department {
    char name[50];
    Employee *employees;
    int employeeCount;
} Department;

// 创建部门
Department* createDepartment(const char *departmentName) {
    Department *department = (Department*)malloc(sizeof(Department));
    if (department == NULL) {
        perror("Memory allocation failed");
        return NULL;
    }
    strcpy(department->name, departmentName);
    department->employees = NULL;
    department->employeeCount = 0;
    return department;
}

// 向部门添加员工
void addEmployee(Department *department, const char *name, const char *position, double salary) {
    department->employees = (Employee*)realloc(department->employees, (department->employeeCount + 1) * sizeof(Employee));
    if (department->employees == NULL) {
        perror("Memory allocation failed");
        return;
    }
    strcpy(department->employees[department->employeeCount].name, name);
    strcpy(department->employees[department->employeeCount].position, position);
    department->employees[department->employeeCount].salary = salary;
    department->employeeCount++;
}

// 释放部门内存
void freeDepartment(Department *department) {
    free(department->employees);
    free(department);
}

int main() {
    int m = 3; // 假设添加3个员工
    Department *department = createDepartment("Engineering");
    if (department == NULL) {
        return 1;
    }

    addEmployee(department, "Alice", "Engineer", 5000.0);
    addEmployee(department, "Bob", "Senior Engineer", 7000.0);
    addEmployee(department, "Charlie", "Manager", 10000.0);

    // 打印部门信息
    printf("Department: %s\n", department->name);
    for (int i = 0; i < department->employeeCount; i++) {
        printf("Employee %d: Name - %s, Position - %s, Salary - %.2f\n", i + 1, department->employees[i].name, department->employees[i].position, department->employees[i].salary);
    }

    freeDepartment(department);
    return 0;
}

可能出现内存泄漏的情况及避免方法:

  1. mallocrealloc失败:在调用mallocrealloc后,应立即检查返回值是否为NULL。如果为NULL,表示内存分配失败,此时不应继续使用未初始化的指针,否则可能导致未定义行为。在代码中,每次调用mallocrealloc后都进行了检查,若失败则打印错误信息并采取相应措施(如返回或结束程序)。
  2. 忘记释放内存:在使用完动态分配的内存后,必须调用free函数进行释放。在本代码中,定义了freeDepartment函数,先释放员工数组的内存,再释放部门结构体的内存,从而避免了内存泄漏。如果在程序结束前没有调用freeDepartment函数,那么分配给部门和员工的内存将不会被释放,导致内存泄漏。