本文介绍了这段代码有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 你好, 我是C的新手,我正在阅读K& R,我在本书的代码中找到了 。 K& R表示,释放后释放的东西是不允许的。并以此为例。 for(p = head; p!= NULL; p-> next) free(p); 它有什么问题? 解决方案 至少有两个问题这段代码:p->接下来什么都不做 和p在被释放后被访问。 即使是第一个问题都没有(即代码说'p = p-> next'') 第二个仍然(可能)杀死你的pprogram。 while循环中的for循环如下所示: p = head; while(p!= NULL) { free(p); p = p-> next; } 或许现在为什么在免费后访问p会更清楚? 为了做到这一点,你可以这样做: p_type p = head; p_type last = NULL; while(p!= NULL) { last = p; p = p-> next; free(last); } (其中p_type是某种指针类型)。在这里,你将p的旧值保存到 last,得到你想要的p值,然后*然后*释放保存的旧值。 HTH rlc - 监狱:只是另一种解释语言 Just:监狱使用愚蠢的条款 加入讨论这种语言的定义 ja *********** @ lists.sourceforge.net http://jail-ust.sourceforge.net (发送邮件至 JA *********** @ lists.sourceforge .net ) hello,i am very new to C and i am reading K&R and i cameaccross this code in the book. K&R says that it isincorrect to free something after it has been freedand gives this as an example.for (p=head; p!= NULL; p->next)free(p);what''s wrong with it? 解决方案There are at least two problems with this code: p->next doesn''t do anythingand p is accessed after it''s been freed.Even if the first problem weren''t there (i.e. the code said `p = p->next'')the second would still (possibly) kill your pprogram.The for loop in while form looks like this:p = head;while (p != NULL){free(p);p = p->next;}perhaps it is a bit clearer now why p is accessed after the free?To do it right, you can do it like this:p_type p = head;p_type last = NULL;while (p != NULL){last = p;p = p->next;free(last);}(in which p_type is some pointer type). Here, you save the old value of p tolast, get the value you want for p, and *then* free the saved, old value.HTHrlc--Jail: Just Another Interpreted LanguageJust: Jail Uses Silly TermsJoin the discussion on the definition of this language at ja***********@lists.sourceforge.net http://jail-ust.sourceforge.net(send mail to ja*********************@lists.sourceforge.net) 这篇关于这段代码有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 07-21 01:09