貝婁是相關代碼:無法將第二個元素插入到鏈表|函數指針被損壞
typedef struct Node_t {
ListElement data;
struct Node_t* next;
} Node;
struct List_t {
Node* head;
Node* tail;
Node* current;
int size;
CopyListElement copyF;
FreeListElement freeF;
};
static ListResult initializeNode(List list, ListElement element, Node* newNode){
printf("\nEntered initializeNode\n");
if ((list == NULL) || (element == NULL)) return LIST_NULL_ARGUMENT;
newNode = malloc(sizeof(Node));
if (newNode == NULL) return LIST_OUT_OF_MEMORY;
printf("\nWithin initializeNode, before copyF\n");
ListElement newElement = list->copyF(element);
printf("\nWithin initializeNode, after copyF\n");
if (newElement == NULL) return LIST_OUT_OF_MEMORY;
newNode->data = newElement;
printf("\nLast line within initializeNode\n");
return LIST_SUCCESS;
}
List listCreate(CopyListElement copyElement, FreeListElement freeElement){
//Check if there is a NULL argument.
if ((copyElement == NULL) || (freeElement == NULL)) return NULL;
//Check wether there is enough memory.
List newList = malloc(sizeof(List));
if (newList == NULL) return NULL;
//Initialize an empty List.
newList->head = NULL;
newList->tail = NULL;
newList->size = 0;
newList->current = NULL;
newList->copyF = copyElement;
newList->freeF = freeElement;
return newList;
}
ListResult listInsertFirst(List list, ListElement element){
printf("\nEntered listInsertFirst\n");
Node* newNode;
ListResult result = initializeNode(list, element, newNode);
printf("\n Node was initialized\n");
if (result != LIST_SUCCESS) {
return result;
}
printf("\nEntering logistic works within listInsertFirst\n");
//Finish logistic work within the Node.
newNode->next = list->head;
list->head = newNode;
list->size++;
printf("\nElement was inserted successfully\n");
printf("\nCheck list->CopyF within listInsertFirst\n");
list->copyF(element);
printf("\nCheck list->CopyF within listInsertFirst: PASSED\n");
return LIST_SUCCESS;
}
在主要功能離子我想:
List list = listCreate(©Int, &freeInt);
ListResult result;
int el=2;
//ListElement e1;
//ListElement e2;
result = listInsertFirst(list,&el);
printf("\nresult = %d\n", result);
result = listInsertFirst(list,&el);
printf("\nresult = %d\n", result);
編譯並運行後我得到:
進入listInsertFirst
copyF
前進入initializeNode
在initializeNode,在init中ializeNode,copyF
內initializeNode最後一行
節點被初始化
進入內listInsertFirst
後勤工作後元素被成功
檢查插入列表 - > CopyF listInsertFirst分段故障之內: 11
由於某種原因,指向[函數] list-> copyF的指針被破壞[我認爲]。
你使用了哪些編譯器標誌?我會嘗試的第一件事是添加-Wall -Wextra。另外,你有沒有試過Valgrind? – 2013-04-29 06:58:13