2016-01-23 48 views
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; 
} 

而现在,这是我如何定义sliststruct node

typedef struct node **slist; 

typedef struct node { 
    void *content; 
    struct node *next; 
} node; 

编辑:奇怪的行为是这样的:当我尝试打印出来的东西,它列出了错误的值。当我使用gdb运行程序时,在第一次拨打sl_size后开始发生。

+0

这是什么行为?会发生什么,你期望发生什么? – AntonH

+0

您能否介绍一下这种“奇怪的行为”究竟是什么?示例输出(错误消息)会很好。 – e0k

+3

嗯,首先,'slist'不是一个指向'struct node'的指针,它是一个指向'struct node'的指针。你对'calloc'的调用分配了错误的大小(它分配一个'struct node',而不是指向一个的指针)。 –

回答

4

问题是您的列表初始化。

您将数组a[]的10个元素添加到您在initialize()中创建的列表中。唯一的问题是你在你的列表节点中存储指向数组a []中数据的指针。不幸的是,这个数组是本地的功能!只要你从initialize()返回,这个数组不再有效,指针指向没有有效的地方了。因此,您希望指向的数字将被“垃圾”值替代。