为什么这个Objective-C代码会引发一个malloc错误?

我用这个方法在object-c中编码base64string,但是这个app有时会崩溃:

- (NSString *) base64Encode { //Point to start of the data and set buffer sizes int inLength = [self length]; int outLength = ((((inLength * 4)/3)/4)*4) + (((inLength * 4)/3)%4 ? 4 : 0); const char *inputBuffer = [self bytes]; char *outputBuffer = malloc(outLength); outputBuffer[outLength] = 0; //64 digit code static char Encode[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; //start the count int cycle = 0; int inpos = 0; int outpos = 0; char temp; //Pad the last to bytes, the outbuffer must always be a multiple of 4 outputBuffer[outLength-1] = '='; outputBuffer[outLength-2] = '='; /* http://en.wikipedia.org/wiki/Base64 Text content M an ASCII 77 97 110 8 Bit pattern 01001101 01100001 01101110 6 Bit pattern 010011 010110 000101 101110 Index 19 22 5 46 Base64-encoded TWF u */ while (inpos < inLength){ switch (cycle) { case 0: outputBuffer[outpos++] = Encode[(inputBuffer[inpos]&0xFC)>>2]; cycle = 1; break; case 1: temp = (inputBuffer[inpos++]&0x03)<<4; outputBuffer[outpos] = Encode[temp]; cycle = 2; break; case 2: outputBuffer[outpos++] = Encode[temp|(inputBuffer[inpos]&0xF0)>> 4]; temp = (inputBuffer[inpos++]&0x0F)<<2; outputBuffer[outpos] = Encode[temp]; cycle = 3; break; case 3: outputBuffer[outpos++] = Encode[temp|(inputBuffer[inpos]&0xC0)>>6]; cycle = 4; break; case 4: outputBuffer[outpos++] = Encode[inputBuffer[inpos++]&0x3f]; cycle = 0; break; default: cycle = 0; break; } } NSString *pictemp = [NSString stringWithUTF8String:outputBuffer]; free(outputBuffer); return pictemp; } 

错误是:

 malloc: *** error for object 0x164084: incorrect checksum for freed object - object was probably modified after being freed. 

当我debugging时,它停在这一行:

 free(outputBuffer); 

你知道这是什么原因造成的吗?

也许这是问题:

 char *outputBuffer = malloc(outLength); outputBuffer[outLength] = 0; 

在第一行中,你分配outLength字节,但是在第二行中,你写了一个超出缓冲区末尾一个字节的位置。 根据malloc页面边界和其他神秘的事件,这可能是好的,也可能不会。 这将解释为什么它不会每次都崩溃。

试试这个:

 char *outputBuffer = malloc(outLength + 1); outputBuffer[outLength] = 0; 

这可能会解决您的问题。

您可以使用以下命令修改过去的malloc'd outputBuffer的末尾:

 outputBuffer[outLength] = 0; 

如果outLength为3,则可以设置outputBuffer[0]outputBuffer[1]outputBuffer[2]但不能设置outputBuffer[3]

要么改变你的malloc:

 char *outputBuffer = malloc(outLength+1); 

或者将您的初始化更改为:

 outputBuffer[outLength-1] = 0;