DevC++编译C双向链表代码报ld returned 1 exit status错误如何解决
问题排查结果
1. ld returned 1 exit status核心原因
- 代码中调用了C标准库不存在的
str()函数,链接器(ld)找不到该函数的实现,直接触发链接错误。该函数是Python等其他编程语言的语法,C语言没有内置整数转字符串的str()函数。 - 如果你确认任务管理器中没有之前运行的同名程序进程,本次报错100%由上述代码问题导致,和DevC++环境无关。
2. 代码其余致命问题
2.1 结构体成员类型不匹配
你定义的Node结构体中data是char单字符类型,但代码中尝试给它赋值字符串、用%s格式符输出,类型完全不兼容,需要修改结构体定义。
2.2 局部栈内存地址滥用
initNode函数中定义的局部字符数组a存放在栈内存中,函数执行结束后该内存会被系统回收,你直接把a的地址赋值给所有节点的data,后续访问会触发野指针问题,且所有节点的data都会指向同一块内存,值会被覆盖。
2.3 缓冲区溢出
你定义的a数组长度只有2(初始值"0"隐含结束符\0,总长度2字节),后续执行strcat(a,"haha")会直接越界写内存,触发未定义行为。
3. 修正后的参考代码
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct Node{ struct Node *prior; char *data; // 修改为char*类型存储字符串 struct Node *next; }Node; Node* initNode(Node *head); void display(Node *head); // 用标准库函数实现整数转字符串逻辑 void int_to_str(int num, char *buf, int buf_size) { snprintf(buf, buf_size, "%d", num); } int main() { Node *head = NULL; head = initNode(head); display(head); printf(":%s:", head->next->next->next->prior->data); // 实际使用请补充链表内存释放逻辑,避免内存泄漏 return 0; } Node* initNode(Node *head){ int i; char num_buf[20]; // 足够存放整数+后缀的缓冲区 head = (Node*)malloc(sizeof(Node)); head->prior = NULL; head->next = NULL; // 构造头节点字符串,单独申请内存存储 int_to_str(1, num_buf, sizeof(num_buf)); strcat(num_buf, "haha"); head->data = (char*)malloc(strlen(num_buf) + 1); strcpy(head->data, num_buf); Node *list = head; for (i = 2; i <= 5; i++) { Node *body = (Node*)malloc(sizeof(Node)); body->prior = NULL; body->next = NULL; // 构造当前节点字符串 int_to_str(i, num_buf, sizeof(num_buf)); strcat(num_buf, "haha"); body->data = (char*)malloc(strlen(num_buf) + 1); strcpy(body->data, num_buf); list->next = body; body->prior = list; list = list->next; } return head; } void display(Node *head){ Node *temp = head; while (temp) { if (temp->next == NULL) { printf("%s\n", temp->data); } else { printf("%s <-> ", temp->data); } temp = temp->next; } }
内容的提问来源于stack exchange,提问作者Mike
相关产品推荐
相关产品推荐

