c - 如何从标准输入读取多行并将其存储在链表中
问题描述
我正在尝试编写一个从用户(来自 STDIN)获取行并将它们存储在链表中的程序。
现在我只得到一行并终止程序。如何更改代码以继续从标准输入获取行?
另外,如果有人可以告诉我我是否正在分配和释放内存,那将非常有帮助。
谢谢。
#include <stdio.h>
#include <stdlib.h>
int BUFF_SIZE = 128;
struct Node {
char* data;
struct Node* next;
};
struct Node* head = NULL;
struct Node* tail = NULL;
void free_list(struct Node* head)
{
if (head != NULL)
{
free_list(head->next);
free(head);
}
}
int main()
{
int curr_size = 0;
char* pStr = malloc(BUFF_SIZE);
curr_size = BUFF_SIZE;
printf("%s", "please print multiple lines\n");
if (pStr != NULL)
{
char c;
int i = 0;
while ((c = getchar()) != '\n' && c != EOF)
{
pStr[i++] = c;
if (i == curr_size)
{
curr_size = i + BUFF_SIZE;
pStr = realloc(pStr, curr_size);
if (pStr == NULL) return;
}
}
pStr[i] = '\0';
struct Node* new_node = malloc(sizeof(struct Node*));
char* new_data = malloc(sizeof(pStr));
new_data = pStr;
new_node->data = new_data;
if (head == NULL)
{
head = new_node;
tail = new_node;
}
else
{
tail->next = new_node;
}
}
free_list(head);
}
解决方案
几个问题:
到目前为止,您在收到
\n
.if (pStr == NULL) return; //error int c; int i = 0; while ((c = getchar()) != EOF) { /*New word, insert into linked list*/ if (c == '\n'){ pStr[i] = '\0'; struct Node* new_node = malloc(sizeof(*new_node)); char* new_data = malloc(i+1); strcpy(new_data, pStr); new_node->data = new_data; if (head == NULL) { head = new_node; tail = new_node; } else { tail->next = new_node; tail = new_node; } i = 0; //Reset the index } else { pStr[i++] = c; if (i == curr_size) { curr_size = i + BUFF_SIZE; pStr = realloc(pStr, curr_size); if (pStr == NULL) return; } } }
内存泄漏和节点
data
将始终指向pStr
.char* new_data = malloc(sizeof(pStr)); new_data = pStr; //Memory leak here new_node->data = new_data;
将其更改为
char* new_data = malloc(i+1); strcpy(new_data, pStr); new_node->data = new_data;
sizeof(pStr) 是指针的大小而不是字符串的长度。
您需要在将
tail
每个节点插入列表后进行更新。else { tail->next = new_node; }
到
else { tail->next = new_node; tail = new_node; }
推荐阅读
- c - 短路 if 语句
- kotlin - Kotlin - Here Maps - 从回调函数中获取地址
- java - 骆驼并行处理随机跳过索引
- python - 熊猫如何防止自己遍历行?
- c# - 在 C# WinForms 数据网格视图中比较具有相同 id 的 2 个连续行并突出显示第 2 行的单元格中的差异?
- datalist - 边缘数据列表出错,不显示超过 10 个选项
- nlp - 我无法将自定义 NER 模型与 CoreNLP 中的现有默认模型集成
- database - 第三范式数据库
- firebase - 推送通知未正确连接到 Firebase 消息传递
- java - Firebase Java Android 检查所有节点子节点的值