matti157
matti157

Reputation: 1288

malloc error when reading file in iOS

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!!!

Upvotes: 0

Views: 198

Answers (1)

Useless
Useless

Reputation: 67733

This part:

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

is broken. strlen just reads until it finds a \0 ... since you didn't put one in, it can just keep reading off the end of your buffer.

You already have size, so just use that, or better still just terminate strRet instead of right-filling with spaces:

strRet[pos] = '\0';

Upvotes: 2

Related Questions