2013-06-03 49 views
0

我有這個函數從字符中逐個字符地讀取一行並將其插入到NSString中。 RANDOMNLY系統崩潰,此錯誤:在iOS中讀取文件時發生malloc錯誤

malloc: *** error for object 0x1e1f6a00: incorrect checksum for freed 
object - object was probably modified after being freed. 
*** set a breakpoint in malloc_error_break to debug 

功能:

NSDictionary *readLineAsNSString(FILE *f,int pospass, 
           BOOL testata, int dimensioneriga) 
{  
    char *strRet = (char *)malloc(BUFSIZ); 
    int size = BUFSIZ; 

    BOOL finito=NO; 
    int pos = 0; 
    int c; 
    fseek(f,pospass,SEEK_SET); 

    do{ // read one line 
     c = fgetc(f); 

     //Array expansion 
     if (pos >= size-1) { 
      size=size+BUFSIZ; 
      strRet = (char *)realloc(strRet, size); 
     } 

     if(c != EOF) { 
      strRet[pos] = c; 
      pos=pos+1; 
     } 
     if(c == EOF) { 
      finito=YES; 
     } 

    } while(c != EOF && c != '\n'); 

    if (pos!=0) { 
     for (int i = pos; i<=strlen(strRet)-1; i++) //size al posto di pos 
     { 
      strRet[i] = ' '; 
     } 
    } 

    NSString *stringa; 
    if (pos!=0) { 
     stringa=[NSString stringWithCString:strRet encoding:NSASCIIStringEncoding]; 
    } else { 
     [email protected]""; 
    } 

    long long sizerecord; 
    if (pos!=0) { 
     sizerecord= (long long) [[NSString stringWithFormat:@"%ld",sizeof(char)*(pos)] longLongValue]; 
    } else { 
     sizerecord=0; 
    } 
    pos = pospass + pos; 

    NSDictionary *risultatoc = @{st_risultatofunzione: stringa, 
           st_criterio: [NSString stringWithFormat:@"%d",pos], 
           st_finito: [NSNumber numberWithBool:finito], 
           st_size: [NSNumber numberWithLongLong: sizerecord] 
           }; 

    //free 
    free(strRet); 
    return risultatoc; 
} 

其中 「finito」 是一個標誌, 「POS」 是在文件中的行的位置, 「pospass」 是位置在整個文件中,「c」是字符,「strRet」是行,並且BUFSIZ是1024.每個文件具有n行,具有相同的長度(對於文件)。

謝謝!

+0

'字符* strRet =(的char *)malloc的(BUFSIZ); '應該是'char * strRet = malloc(BUFSIZ);'。 – 2013-06-03 17:00:17

+0

@ H2CO3 - 您的陳述對於C來說是正確的,對於C++來說是錯誤的,是否正確,objective-c不需要類型轉換呢?我讀過:'「Objective-C語法是GNU C/C++語法的超集」# – Mike

+1

@Mike這是錯誤的,Objective-C是C的一個嚴格超集。因此,在談論Objective-C時,**從來沒有人關心C++的缺陷。 – 2013-06-03 18:15:16

回答

2

這部分:

if (pos!=0) { 
    for (int i = pos; i<=strlen(strRet)-1; i++) //size al posto di pos 
    { 
     strRet[i] = ' '; 
    } 
} 

壞了。 strlen只是讀取,直到找到一個\0 ...因爲您沒有放入,它可以繼續讀取緩衝區的末尾。

您已經size,所以只使用,或者更好的是剛剛結束strRet,而不是用空格右填充:

strRet[pos] = '\0'; 
+0

謝謝...現在它工作 –

相關問題