0
我已經實現了一個單鏈表,並且我注意到非常奇怪的行爲,但無法確定它發生的確切原因。我試過用gdb
來找出問題所在,看起來像每當我計算一個列表的大小,那就是當事情開始出錯的時候。這是我用來測試我的實現的程序,以下是實際的實現。C未定義的行爲 - 單鏈表
#include <stdio.h>
#include "singlylinked.h"
slist initialize(void); /* initializes test singly linked list */
slist initialize(){
int i, a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
slist l = sl_alloc();
int a_size = sizeof(a)/sizeof(a[0]);
for(i=0;i<a_size;i++){
sl_add(l, (void *)&a[i]);
}
return l;
}
int main(){
slist l = initialize();
int i, size = sl_size(l);
for(i = 0; i < size; i++){
printf("%d ", *(int *)sl_get(l,i));
}
fputc('\n',stdout);
return 0;
}
而現在的實際執行中,我將只發布在測試中使用的方法:
/* allocates an empty slist */
slist sl_alloc(){
return (slist) calloc(1, sizeof(struct node));
}
/* adds val to linked list */
void sl_add(slist l, void *val){
node *current, *new;
new = calloc(1, sizeof(struct node));
new->content = val;
new->next = NULL;
if((current = *l)){
while(current->next){
current = current->next;
}
current->next = new;
} else {
*l = new;
}
}
/* returns ith value in singly linked list l */
void *sl_get(slist l, int i){
node *current;
int j; /* counter */
void *result = NULL;
if((current = *l)){
int size = sl_size(l);
if(i < size){
for(j = i; j > 0; j--){
current = current->next;
}
result = current->content;
}
}
return result;
}
/* returns the size of the singly linked list */
int sl_size(slist l){
int size = 0;
node *current;
if((current = *l)){
do {
size++;
current = current->next;
} while (current);
}
return size;
}
而現在,這是我如何定義slist
和struct node
:
typedef struct node **slist;
typedef struct node {
void *content;
struct node *next;
} node;
編輯:奇怪的行爲是這樣的:當我嘗試打印出來的東西,它列出了錯誤的值。當我使用gdb
運行程序時,在第一次撥打sl_size
後開始發生。
這是什麼行爲?會發生什麼,你期望發生什麼? – AntonH
您能否介紹一下這種「奇怪的行爲」究竟是什麼?示例輸出(錯誤消息)會很好。 – e0k
嗯,首先,'slist'不是一個指向'struct node'的指針,它是一個指向'struct node'的指針。你對'calloc'的調用分配了錯誤的大小(它分配一個'struct node',而不是指向一個的指針)。 –