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