2012-10-07 53 views
0

我有一个程序创建一个排序后的链接列表,它在测试之后可用于创建列表。尝试删除列表中的元素时出现问题。这些类型是隐藏的,在代码中您将看到参数void* newObj,并且该结构具有用于进行实际比较的函数指针。具有数据结构指针参数的C函数

我的代码segfaults,我相信这是因为列表的头没有更新,所以传递值的问题,但我不知道如何解决它。

功能:

int SLRemove(SortedListPtr list, void *newObj) 
{ 
    SortedListPtr temp; 
    SortedListPtr temp2; 

    if(list->CompareFcn(newObj, list->value) == 0) 
    { 
     if(list->flag == 1) 
     { 
      return 0; 
     } 
     temp = list; 
     list = list->next; 
     printf("(if)Address of object: %p with value %d, freed.\n", temp, *(int*)temp->value); 
     free(temp); 
     printf("New head of list is, address: %p, value: %d.\n", list, *(int*)list->value); 
     return 1; 
    } 
    for (temp = list; temp != NULL; temp = temp->next) 
    { 
     printf("Address of TEMP: %p\n", temp); 
     temp2 = temp->next; 
     if(temp2->CompareFcn(newObj, temp2->value) == 0)/*value == *newObj*/ 
     { 
      temp->next = temp2->next; 
      printf("(loop)Address of object: %p, freed.\n", temp2); 
      free(temp2); 
      return 1; 
     } 
    } 

    return 0; 
} 

来电:

for (icount = 1; icount <= 3; icount += 1) 
    { 
     *ptr[icount-1] = icount; 
     printf("Removing...\n"); 
     printf("Current head of list to be removed, address: %p, value: %d.\n", integerList, *(int*)integerList->value); 
     if (SLRemove(integerList, ptr[icount-1]) == 1) 
     { 
      printf("SLRemove number %d, success!\n\n", icount); 
      free(ptr[icount-1]); 
     } 
     else 
     { 
      printf("SLRemove number %d failed!\n\n", icount); 
     } 
    } 

Valgrind的:

Removing... 
Current head of list to be removed, address: 0x51f1040, value: 1. 
Comparing newObj: 1 and item: 1. Returning 0. 
(if)Address of object: 0x51f1040 with value 1, freed. 
New head of list is, address: 0x51f1140, value: 2. 
SLRemove number 1, success! 

==23304== Invalid read of size 8 
==23304== at 0x400826: main (main.c:63) 
==23304== Address 0x51f1040 is 0 bytes inside a block of size 32 free'd 
==23304== at 0x4C2A82E: free (in /usr/lib/valgrind/vgpreload_memcheck-amd64-linux.so) 
==23304== by 0x400B8D: SLRemove (sorted-list.c:176) 
==23304== by 0x400805: main (main.c:60) 
==23304== 
+0

答案是 “是的”,[见这里](http://stackoverflow.com/a/12449034/596781)一一般配方,也[这里](http://stackoverflow.com/a/8435899/596781)和[这里](http://stackoverflow.com/a/12059728/596781)。 –

回答

1

您正在修改list内SLRemove(),但因为它是按值传递,这种变化永远不会回到调用者。尽量

int SLRemove(SortedListPtr *list_ptr, void *newObj) 
{ 
    SortedListPtr list = *list_ptr; 
    . 
    . 
    . 
    *list_ptr = list; 
    return 1; 
    . 
    . 
    . 
} 

当你调用它,使用:

if (SLRemove(&integerList, ptr[icount-1]) == 1) 
+0

这也需要将函数签名更改为'SortedListPtr * list',我想。 –

+0

@KerrekSB:啊,C,不是C++ ..我的错误。 –

+0

@KerrekSB:固定 –