更新时间:2023-02-17 18:11:56
您可能会误以为您的赋值语句:
You may be under the false impression that your assignment statement:
tempNode->itemName = tempName;
将整个字符串从一个位置复制到另一个位置.在许多其他编程语言中,可能是这种情况.在C中不是这样.
copies the entire string from one place to another. In many other programming languages this may be the case; not so in C.
此语句所做的全部工作就是将缓冲区 tempName
的内存地址复制到指针变量 tempNode-> itemName
中.这有两种错误.
All this statement does, is copy the memory address of buffer tempName
into the pointer variable tempNode->itemName
. This is wrong in two ways.
tempName
是自动变量.一旦程序流离开函数 load
,就很可能会回收其内存.此后,链表继续引用该内存.这是导致未定义行为的主要错误.tempName
is an automatic variable. Its memory is likely to be reclaimed as soon as the program flow leaves function load
. The linked list keeps on referring to that memory afterwards. This is a major bug that leads to undefined behavior.解决方案是复制字符串.使用功能 strdup
可以很容易地做到这一点.只需替换以下代码:
The solution is to duplicate the string. This is easy to do with function strdup
. Just replace this line of code:
tempNode->itemName = tempName;
作者:
tempNode->itemName = strdup(tempName);