1

我正在用 c 编写一个简单的双向链表实现,我创建了如下结构。

typdef struct node{
  void *data;
  struct node *next, *prev;
}node;

typedef struct list{
  struct node *head, *tail;
  size_t size;
}list;

我正在使用此功能在我的链接列表中插入元素,一切似乎都正常。假设我用整数填充我的列表,调用函数 4 次以插入 {2,4,6,8}。当我执行打印功能时,它正确返回 2、4、6、8。

void insert_node(list *l, void *elem)
{
  node *n = create_node(elem); //here i just create and initialize the new node;
  if(l->size == 0){
    l->head = n;
    l->tail = n;
  }else{
    l->tail->next = n;
    n->prev = l->tail;
    l->tail = n;
  }
  l->size++;
}

当我尝试统一测试我的功能时,问题就出现了,我编写了这个简单的单元测试:

void test_list_insert(){
 list *l = list_test(); //this function creates a list and inserts in it {2,4,6,8} as values
 TEST_ASSERT_EQUAL_INT(2, *(int*)(get_node_i(l,0))->data);
 TEST_ASSERT_EQUAL_INT(4, *(int*)(get_node_i(l,1))->data); //problem seems to be here..
 TEST_ASSERT_EQUAL_INT(6, *(int*)(get_node_i(l,2))->data);
 TEST_ASSERT_EQUAL_INT(8, *(int*)(get_node_i(l,3))->data);
}

当我执行单元测试时,我得到这个输出:

test.c:73:test_list_insert:FAIL Expected 4 was 1

此时问题似乎与'get_node_i'函数有关,该函数用于检索列表第i个位置的元素......这是函数:

node *get_node_i(list *l, int pos){
 if(pos > l->size || pos < 0){
   return NULL;
 }
 node *curr = l->head;
 int currPos = 0;
 if(pos == 0) return curr;
 while(curr != NULL){
   if(currPos == pos){
     return curr; 
   }
   currPos++;
   curr = curr->next;  
 }
 return NULL;
}

我试图在单元测试中执行我的打印功能,我发现它只正确打印前两个节点(2,4),而对于其他节点,它打印指针......这对我来说很奇怪,好像我尝试在我的代码的任何其他部分执行打印功能,它会正确返回列表..

这是我创建列表和节点的方式

//create new node
node* create_node(void * elem){
  node *n = (node *)malloc(sizeof (node));
  n->data = elem;
  n->next = NULL;
  n->prev = NULL;
  return n;
}
//create an empty list
list  *create_list(){
  list *l = (list *)malloc(sizeof(list));
  l->size = 0;
  l->head = NULL;
  l->tail = NULL;
  return l;
}

这是 list_test 函数和 print 函数,

list* list_test(){
   list *l = create_list();
   int a = 2;
   int b = 4;
   int c = 6;
   int d = 8;
   insert_node(l, &a);
   insert_node(l, &b);
   insert_node(l, &c);
   insert_node(l, &d);
   return l;

}


//print the list
void print_list(list *l){
  node *tmp = l->head;
  while(tmp != NULL){
    printf("%d\t" , *(int *)tmp->data);
    tmp = tmp->next;
  }
}

如果还有什么需要澄清的,请告诉我,谢谢。

4

1 回答 1

0

在您的函数list_test中插入局部变量的地址。所以node->data被分配了一个局部变量的地址。当函数返回时,这些地址指向的数据会发生变化。

该函数list_test应类似于以下内容:

list* list_test(){
   list *l = create_list();
   int a = 2, *ap = malloc(sizeof(int));
   int b = 4, *bp = malloc(sizeof(int));
   int c = 6, *cp = malloc(sizeof(int));
   int d = 8, *dp = malloc(sizeof(int));
   *ap = a;
   *bp = b;
   *cp = c;
   *dp = d;
   insert_node(l, ap);
   insert_node(l, bp);
   insert_node(l, cp);
   insert_node(l, dp);
   return l;
}


于 2020-01-10T15:37:17.370 回答