2011-03-22 63 views
0
Test Case '-[TestParse testParsing]' started. 
/Developer/Tools/RunPlatformUnitTests.include: line 415: 3256 Segmentation fault "${THIN_TEST_RIG}" "${OTHER_TEST_FLAGS}" "${TEST_BUNDLE_PATH}" 
/Developer/Tools/RunPlatformUnitTests.include:451: error: Test rig '/Developer/Platforms /iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk/Developer/usr/bin/otest'  
exited abnormally with code 139 (it may have crashed). 

當我隨機構建測試用例時(有時它成功構建,有時會引發seg故障),我得到了這個seg錯誤消息。我不知道如何解決這個錯誤。 我在這裏測試的唯一事情是我寫了一個類名解析類級別的方法。而在測試情況下,我只是把它像xcode中的單元測試:不一致的構建結果

var = [Parse methodName:filepath]; 

方法是這樣的

NSMutableDictionary *tempBox = [[NSMutableDictionary alloc] init]; 
FILE *fd = fopen([filePath UTF8String], "r"); 
if(!fd){ 
    NSLog(@"fail to open file\n"); 
} 
char buf[4096], *ptr; 
char name[512], description[4096]; 
int isNewInfo = 2, description_continue = 0; 

// for (line = 0; line < [args objectAtIndex:1]; line++) { 
//  fgets(buf, 4096, fd); 
// } 

while(fgets(buf, sizeof(buf), fd) != NULL){ 
    if(strcmp(buf, "\n") == 0){ 
     isNewInfo -= 1; 
     if(isNewInfo == 0){ 
      isNewInfo = 2; 
      description_continue = 0; 
      description[strlen(description)-1] = '\0'; 
      [self saveDrinkandResetBuf:name 
        detail:description box:tempBox]; 
      if(name[0] != 0 || description[0] != 0){ 
       NSLog(@"fail to reset..."); 
      } 

     } 
    } 
    if(description_continue){ 
     strcat(description, buf); 
     continue; 
    } 
    if((ptr = strstr(buf, "Drink Name: "))){ 
     memcpy(name, buf+12, strlen(buf)); 
     name[strlen(name)] = '\0'; 
     continue; 
    } 
    if((ptr = strstr(buf, "Description: "))){ 
     memcpy(description, buf+13, strlen(buf)); 
     description_continue = 1; 
     continue; 
    } 
} 
fclose(fd); 
NSLog(@"finish parsing section\n"); 
//[tempBox release]; 
return tempBox; 

不知道這到底是怎麼回事..

+0

請發送'methodName:'代碼。 – amattn 2011-03-22 05:13:51

+0

目前它看起來像你在返回時正在泄漏tempBox – nduplessis 2011-03-22 05:40:15

+0

即時通訊仍然相當困惑釋放(即時通訊仍然不是很熟悉Obj-c)。我認爲釋放在c中是免費的,所以我傾向於釋放任何稱爲這種方法的內存。 – 2011-03-22 05:49:21

回答

2

我想,這個問題是在陣列管理。

在C語言中,如果數組在函數中聲明(並且未聲明爲全局或靜態),則其元素的值是未定義的。所以你的char description[4096]充滿了任何值。沒有人說''0'會在那裏。

而對於非空終止的char字符串,strlen(...)的結果未定義。它可能導致內存訪問衝突,因爲它會繼續計數,直到到達第一個存儲字節,其值爲0

而且,當你調用description[strlen(description)-1]strlen可以返回0(設想的第一個值,存儲在那裏最初是'\ 0',並且您的文件開始時有兩條空行[達到此行代碼]) - 因此數組索引將爲-1 ...

+0

好趕上!在其他方面,我有點懷疑strlen。 – 2011-03-22 06:59:55