2013-06-03 6 views
0

파일에서 문자를 한 줄씩 읽은 다음이를 NSString에 삽입하는이 함수가 있습니다.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 

기능 :

플래그는 "POS"는 파일의 라인의 총수는 "finito"
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; 
} 

는 "pospass는"위치이다 RANDOMNLY 시스템이 오류로 충돌 전체 파일에서 "c"는 문자이고 "strRet"은 줄이며 BUFSIZ는 1024입니다. 각 파일의 길이는 n 줄입니다 (파일의 경우).

감사합니다 !!!

+0

'문자 * strRet = (숯불 *)의 malloc (BUFSIZ); ''char * strRet = malloc (BUFSIZ); '이어야합니다. –

+0

@ H2CO3 - 귀하의 진술은 C에 대해 사실이며, C++에 대해서는 거짓입니다. 그 objective-c는 (는) 타입 변환도 필요하지 않습니다. 나는 그것을 읽었습니다 :''Objective-C 구문은 GNU C/C++ 구문의 상위 집합입니다. "' – Mike

+1

@Mike 틀 렸습니다, Objective-C는 Objective-C에 대해 말할 때 ** 매우 엄격합니다. ** 어느 누구도 ** C++의 결함에 관심이 없습니다. –

답변

2

이 부분 :

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

이 끊어집니다. strlen\0을 발견 할 때까지 그냥 읽습니다. 넣지 않았으므로 버퍼의 끝에서 계속 읽을 수 있습니다.

은 이미 그래서 단지를 사용하거나 더 나은 여전히 ​​공백으로 권리를 채우는 대신 strRet을 종료size 있습니다

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

감사합니다 ... 이제 작동합니다. –

관련 문제