我有这个函数,从文件中逐字符读取一行,并将其插入到NSString中。系统随机崩溃,出现以下错误:
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 {
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;
}
,其中"finito"是一个标志,"pos"是文件行的位置,"pospass"是整个文件中的位置,"c"是字符,"strRet"是行,bufsize是1024。每个文件有n行相同的长度(对于文件)。
谢谢! !
这部分:
if (pos!=0) {
for (int i = pos; i<=strlen(strRet)-1; i++) //size al posto di pos
{
strRet[i] = ' ';
}
}
坏了。strlen
只是读取,直到找到