0

i have this function that reads a line from a file character by character and inserts it into a NSString. RANDOMNLY the system crashes with this error:

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

function:

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 {
        stringa=@"";
    }

    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;
}

where "finito" is a flag, "pos" is the position in the file line,"pospass" is the position in the entire file, "c" is the character, "strRet" is the line and BUFSIZ is 1024. Each file has n line with the same lenght (for file).

Thanks!!!

4

1 回答 1

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';
于 2013-06-03T16:59:07.863 回答