我试图删除链表上的所有节点,但我遇到了分段错误。删除链表时出现分段错误
我有最初工作的代码,但我只是删除列表中的第一个节点,我想删除所有节点并删除所有指针冗余指针。
此外,如果你们中的一些人可以检查我用来创建链接列表的功能,并给我一些反馈意见,你是否认为它是好的或者可以做出一些改进,我将不胜感激。
谢谢。
下面是代码:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define MEMORY_SIZE (15)
typedef struct link {
double coeff;
int pow;
struct link * next;
} poly;
poly *polyArray[MEMORY_SIZE];// array of 15 polynomials to play with
// /** The function prototypes */
void createPoly(poly **);
void deletePoly(poly *);
/**
* The main function
*/
int main(void) {
printf("\n\n\t***************************************************");
/* printf("\n\tDemonstrating Polynomial Creation");
printf("\n\t***************************************************");*/
printf("\n\t1st polynomial\t");
createPoly(&polyArray[0]);
showPoly(polyArray[0]);
srand(time(NULL));
// printf("\n\n\tCreating and storing the 2nd polynomial\n");
// createPoly(&polyArray[1]);
// showPoly(polyArray[1]);
showPoly(polyArray[0]);
printf("\n\t***************************************************");
printf("\n\tProgram has Ended, Deleting all polynomials");
printf("\n\t***************************************************");
int count;
for(count = 0; count < MEMORY_SIZE; count++)
{
deletePoly(polyArray[count]);
}
printf("\n\n");
showPoly(polyArray[0]);
return 0;
}//end main function
//////////////////////////////////////////////////////////////////////////////////////
void createPoly(poly **node) {
poly *tempnode; //To hold the temporary last address
tempnode = (poly*)malloc(sizeof(poly)); //create the first node
*node = tempnode; //Store the head address to the reference variable
int flag = 1 + rand()%3;; // A flag to control the number of terms
int counter;
for(counter = 0; counter <= flag; counter++)
{
tempnode->pow = (flag-counter);
tempnode->coeff = ((double)(rand()%20))/((double)(1 + rand()%20));
if((counter < flag) && (counter >= 0) )
{
tempnode->next = (poly*)malloc(sizeof(poly)); //Grow the list
}
else if (counter == flag)
{
tempnode->next = NULL;
}
tempnode = tempnode->next;
}
}
void deletePoly(poly *node) {
poly *temp;
if(node->next == NULL)
{
free(node);
node = NULL;
}
else
{
while(node->next != NULL)
{
temp = node->next;
free(node);
node = temp;
}//end while
node = NULL;
}//end 'if/else'
}//end function 'deletePoly'
的错误是在'deletePoly' – 2014-11-22 02:02:00
好,谢谢,我假设它在poly中的while循环内,我是否正确? – SlamDunkMonk 2014-11-22 02:04:08
你不检查'if(!node)'。 – EOF 2014-11-22 02:07:00