handleInsert函数插入电阻异常(R1->R2->R1场景)求助
问题:handleInsert函数插入重复标签时出现异常行为
异常现象
- 操作流程:添加标签R1(阻值500Ω)→ 添加标签R2(阻值500Ω)→ 再次添加标签R1(阻值500Ω),程序输出异常内容:
V -1984934880 Ohms
R2 500 Ohms - 正常对比:连续两次添加R1(500Ω),程序正确提示
A resistor with R1 label already exists.,并显示:R1 500 Ohms
- 其他无「R1→R2→R1」的操作场景均符合预期,已定位问题出在
handleInsert函数中。
问题代码
void handleInsert(LinkedList* circuit) { int resistance; printf("What's the value of the resistor: "); readInputNumber(&resistance); printf("What's the label of the resistor: "); char labelName[STRING_MAX]; readInputString(labelName, STRING_MAX); Node* current = circuit->head; Node* prev = NULL; // Check if a resistor with the same label already exists while (current != NULL) { if (strcmp(current->name, labelName) == 0) { printf("A resistor with %s label already exists.\n", labelName); return; } prev = current; current = current->next; } Node* newNode = (Node*)malloc(sizeof(Node)); if (newNode == NULL) { printf("Memory allocation failed.\n"); return; } newNode->value = resistance; strcpy(newNode->name, labelName); newNode->next = NULL; if (prev == NULL) { circuit->head = newNode; } else { prev->next = newNode; } }
问题分析与解决
核心原因
问题出在新节点的name字段内存未正确分配:
如果你的Node结构体定义中,name是char*类型(而非固定大小的字符数组),那么malloc(sizeof(Node))仅分配了结构体本身的内存,newNode->name是未初始化的野指针。此时调用strcpy(newNode->name, labelName)会向随机内存地址写入数据,导致内存越界,破坏已存在的链表节点数据(比如篡改了R1节点的name或value)。
当第三次插入R1时,遍历链表时无法识别被篡改的R1节点,错误地执行插入操作,进一步加剧内存破坏,最终出现异常输出。
解决方法
根据Node结构体的定义,选择以下两种修复方式之一:
方式1:将Node的name定义为固定大小数组
确保数组长度不小于STRING_MAX,避免越界:
#define STRING_MAX 64 // 根据实际需求调整 typedef struct Node { int value; char name[STRING_MAX]; // 固定大小数组,足够容纳输入标签 struct Node* next; } Node;
方式2:为name单独分配内存(当name是char*时)
在创建新节点后,先为name分配足够的内存,再执行字符串复制:
Node* newNode = (Node*)malloc(sizeof(Node)); if (newNode == NULL) { printf("Memory allocation failed.\n"); return; } // 为name分配内存,+1用于存储字符串结束符'\0' newNode->name = malloc(strlen(labelName) + 1); if (newNode->name == NULL) { printf("Memory allocation for label failed.\n"); free(newNode); // 释放已分配的节点内存,避免泄漏 return; } newNode->value = resistance; strcpy(newNode->name, labelName); newNode->next = NULL;
额外检查
确认readInputString函数正确地在输入字符串末尾添加了'\0',否则会导致strcmp比较时读取到错误的内容,引发逻辑判断错误。
内容的提问来源于stack exchange,提问作者Alya Bayer
相关产品推荐
相关产品推荐

