makeNode函数存在哪些问题?请帮忙排查我的C语言代码错误
代码中的错误分析
1. 拷贝函数传值传递导致数据无法写入节点
你的cpy函数采用传值传递参数:
void cpy(dl x, dl a) { // ... }
调用cpy(p->x, a)时,x是p->x的临时副本,函数内对x的修改仅作用于副本,不会影响原节点的p->x。这会导致创建的节点中dl类型的数据未被正确赋值,后续打印p->x会得到随机垃圾值。
修复方案:将第一个参数改为指针类型,直接操作原结构体:
void cpy(dl *x, const dl *a) { strcpy(x->ProblemID, a->ProblemID); strcpy(x->TimePoint, a->TimePoint); strcpy(x->Status, a->Status); x->Point = a->Point; printf("%s %s %s %d\n",x->ProblemID,x->TimePoint,x->Status,x->Point); }
调用时改为:
cpy(&p->x, &a);
2. 字符串拷贝存在缓冲区溢出风险
strcpy不会检查目标数组的长度,如果源字符串长度超过目标数组的定义(比如ProblemID仅10字节,源字符串长度≥10),会触发缓冲区溢出,导致未定义行为。
修复方案:改用安全的strncpy,手动补终止符:
strncpy(x->ProblemID, a->ProblemID, sizeof(x->ProblemID)-1); x->ProblemID[sizeof(x->ProblemID)-1] = '\0'; // 其他字符串字段同理处理
3. 缺少必要的头文件
代码使用了malloc、exit、strcpy、printf等函数,但未包含对应头文件,会导致编译警告或错误:
malloc/exit需要<stdlib.h>strcpy/strncpy需要<string.h>printf需要<stdio.h>
需在代码开头添加:
#include <stdio.h> #include <stdlib.h> #include <string.h>
4. 可优化的细节
makeNode的参数dl a可改为const dl *a,避免不必要的结构体拷贝,同时明确不会修改原数据。- C语言中
malloc的返回值无需强制转换为Node*,强制转换反而可能隐藏头文件缺失的编译警告。
修复后的完整代码示例
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct _dl { char ProblemID[10]; char TimePoint[20]; char Status[10]; int Point; } dl; typedef struct _Node { dl x; struct _Node* leftChild; struct _Node* rightChild; } Node; void cpy(dl *x, const dl *a) { strncpy(x->ProblemID, a->ProblemID, sizeof(x->ProblemID)-1); x->ProblemID[sizeof(x->ProblemID)-1] = '\0'; strncpy(x->TimePoint, a->TimePoint, sizeof(x->TimePoint)-1); x->TimePoint[sizeof(x->TimePoint)-1] = '\0'; strncpy(x->Status, a->Status, sizeof(x->Status)-1); x->Status[sizeof(x->Status)-1] = '\0'; x->Point = a->Point; printf("%s %s %s %d\n",x->ProblemID,x->TimePoint,x->Status,x->Point); } Node* makeNode(const dl *a) { Node* p = malloc(sizeof(Node)); if (p == NULL) { exit(1); } cpy(&p->x, a); printf("%s %s %s %d\n",p->x.ProblemID,p->x.TimePoint,p->x.Status,p->x.Point); p->leftChild = NULL; p->rightChild = NULL; return p; }
内容的提问来源于stack exchange,提问作者Trang Bùi
相关产品推荐
相关产品推荐

