有两个功能,一个是创建链接列表,另一个是释放链接列表。
如果Create函数返回指向头节点的双指针,则使用该节点释放链接列表,将遇到段错误。但是,如果更改Create函数以返回指向头节点的指针,然后释放列表,则可以。
谁能为我解释一下?以下是存在段错误的代码:
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode{
int m_nValue;
ListNode* m_pNext;
}ListNode;
ListNode** CreateList(int data[], int length){
if(length<=0 || data == NULL)
return NULL;
ListNode *pHead = (ListNode*)malloc(sizeof(ListNode));
ListNode *pNode = pHead;
pNode->m_pNext = NULL;
pNode->m_nValue = data[0];
int i=1;
for(; i<length; i++){
ListNode *temp = (ListNode*)malloc(sizeof(ListNode));
temp->m_nValue = data[i];
temp->m_pNext = NULL;
pNode->m_pNext = temp;
pNode = temp;
}
return &pHead;
}
void FreeList(ListNode **pHead){
ListNode *pNode;
while(pHead!=NULL && *pHead!=NULL){
pNode = *pHead;
*pHead = pNode->m_pNext; // here will encounter an error;
free(pNode);
}
pHead = NULL;
}
int main(){
int data[] = {1,2,3,4,5};
ListNode **pHead = CreateList(data, sizeof(data)/sizeof(int));
FreeList(pHead);
}
但是,如果我将CreateList的返回类型更改为ListNode * CreateList(...),它将很好地工作。
ListNode* CreateList(int data[], int length){
if(length<=0 || data == NULL)
return NULL;
ListNode *pHead = (ListNode*)malloc(sizeof(ListNode));
ListNode *pNode = pHead;
pNode->m_pNext = NULL;
pNode->m_nValue = data[0];
int i=1;
for(; i<length; i++){
ListNode *temp = (ListNode*)malloc(sizeof(ListNode));
temp->m_nValue = data[i];
temp->m_pNext = NULL;
pNode->m_pNext = temp;
pNode = temp;
}
return pHead;
}
int main(){
int data[] = {1,2,3,4,5};
ListNode *pHead = CreateList(data, sizeof(data)/sizeof(int));
FreeList(&pHead);
}
最佳答案
在ListNode** CreateList(int data[], int length)
方法中,您将返回指向局部变量的指针,该局部变量在函数返回时显然变得无效。
也就是说,您在ListNode* pHead
函数中声明了一个指针变量CreateList
,并返回了该变量pHead
的地址。指针变量pHead
存储在堆栈中,当CreateList函数返回堆栈时,即使pHead
指向的内存仍然在堆上,也会释放用于存储pHead
的展开内存。
关于c++ - 在空闲列表期间,存在一个段错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22123952/