且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将单词保存到C中的链接列表的问题

更新时间: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.

  1. 通过反复执行此操作,最终链表中的 all 个节点都引用了相同的字符串缓冲区.该缓冲区被重复覆盖;最后,剩下的就是从文件读取的最后一行.无论您访问哪个节点,都将始终看到相同的字符串.
  2. tempName 自动变量.一旦程序流离开函数 load ,就很可能会回收其内存.此后,链表继续引用该内存.这是导致未定义行为的主要错误.
  1. By repeatedly doing this, eventually all nodes in your linked list have a reference to the same string buffer. This buffer is overwritten repeatedly; at the end, all that is left is the last line read from file. Whatever node you access, you will always see that same string.
  2. 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);