#include <stdio.h>
#include <stdlib.h>
// 定义结构体
struct Level3 {
int data;
};
struct Level2 {
struct Level3 *ptr;
};
struct Level1 {
struct Level2 *ptr;
};
int main() {
// 创建结构体实例并初始化各级指针
struct Level1 *level1 = (struct Level1 *)malloc(sizeof(struct Level1));
if (level1 == NULL) {
perror("malloc for Level1");
return 1;
}
struct Level2 *level2 = (struct Level2 *)malloc(sizeof(struct Level2));
if (level2 == NULL) {
perror("malloc for Level2");
free(level1);
return 1;
}
struct Level3 *level3 = (struct Level3 *)malloc(sizeof(struct Level3));
if (level3 == NULL) {
perror("malloc for Level3");
free(level2);
free(level1);
return 1;
}
level1->ptr = level2;
level2->ptr = level3;
level3->data = 42;
// 访问最内层data成员
if (level1 != NULL && level1->ptr != NULL && level1->ptr->ptr != NULL) {
printf("The value of data is: %d\n", level1->ptr->ptr->data);
} else {
printf("There is a null pointer, cannot access data.\n");
}
// 释放内存
free(level3);
free(level2);
free(level1);
return 0;
}
空指针风险及避免方法
- 风险:在创建结构体实例时,如果
malloc
分配内存失败,会返回空指针。例如,在malloc
为Level1
、Level2
或Level3
分配内存失败时,如果没有进行空指针检查,后续对指针的解引用操作(如level1->ptr
)就会导致未定义行为,程序可能崩溃。
- 避免方法:每次使用
malloc
分配内存后,立即检查返回值是否为NULL
。如上述代码中,在每次malloc
后都进行了空指针检查,如果分配失败,及时释放之前已分配的内存,并给出错误提示,避免后续的空指针引用问题。在访问最内层data
成员时,也要先检查各级指针是否为NULL
,确保指针有效后再进行解引用操作。