【发布时间】:2020-01-10 14:11:03
【问题描述】:
我正在用 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函数和打印函数,
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;
}
}
如果还有什么需要澄清的,请告诉我,谢谢。
【问题讨论】:
-
有一个minimal reproducible example 以确保所有部分都正确完成,包括创建节点
-
this function creates a list and inserts in it {2,4,6,8} as values- 当我看到它时我会相信。 -
我正在发布函数
标签: c unit-testing data-structures linked-list unity-test-framework