【发布时间】:2020-06-28 22:48:51
【问题描述】:
我有这个函数应该复制链表中的一个节点(不是第一个)
struct Node {
char* data;
Node* next;
};
void Insert(Node*head, int index, char* data) {//find a is function to find needed position
Node* temp = find(head, index);
Node* t = (Node*)malloc(sizeof(Node));
t->data = (char*)malloc(100);//where the problem is //line 4
strcpy(t->data, data);
t->next = temp->next;
temp->next = t;
}
如果第 4 行在我的代码中,它将运行良好。我读过这个问题:
crash-or-segmentation-fault-when-data-is-copied-scanned-read-to-an-uninitializ
所以我知道指针不能包含任何数据,我不能将数据复制/存储到指针中。所以,如你所见,我先为其分配了内存,然后将数据放入其中,否则我的程序将崩溃。
但是后来我用了这个:t->data = data;,它起作用了,所以我想知道:为什么当我像这样strcpy(t->data, data);使用strcpy时,我需要先为t->data分配内存,否则我的程序会碰撞;但是这个t->data = data; 可以很好地工作,不需要分配内存?
你能给我解释一下吗?
PS:强制转换 malloc 是因为使用了 c++ 编译器。
【问题讨论】:
-
阿德里安是正确的。此外,您可以使用:
t->data = strdup(data);事实上,100是hardwired。如果data的字符数超过 100 个,则说明您分配的空间不足。 -
@AdrianMole 抱歉。实际上这是我问的另一个问题,有人告诉我这是错误的。我会编辑它。谢谢。
-
请贴出所有需要重现的代码。
Node是什么?data内存是如何管理的?it worked究竟是什么? Do not cast result of malloc。请发帖minimal reproducible example。 -
@KamilCuk 我添加了它。对不起
-
通常你需要提供A Minimal, Complete, and Verifiable Example (MCVE) -- 但是这里的分配和其他错误是显而易见的。
标签: c memory memory-management linked-list c-strings