2012-10-07 4 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

넌 SLRemove() 안에 list 수정되지만,이 값에 의해 전달되기 때문에, 그 변화 발신자에게 결코 돌아 가지 않습니다. 당신이 사용을 호출 할 때

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 : 고정 –