为什么此Objective-C代码会引发malloc错误? [英] Why does this Objective-C code raise a malloc error?
问题描述
我使用此方法在object-c中编码base64字符串,但该应用有时崩溃了:
I used this method to encode base64 string in object-c, but the app was crashed sometimes:
- (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 a n
ASCII 77 97 110
8 Bit pattern 01001101 01100001 01101110
6 Bit pattern 010011 010110 000101 101110
Index 19 22 5 46
Base64-encoded T W F 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.
当我调试时,它会在这一行停止:
and when I debug, it stop in this line:
free(outputBuffer);
您知道是什么原因导致撞车吗?
Do you know what caused crash here ?
推荐答案
也许是问题所在
char *outputBuffer = malloc(outLength);
outputBuffer[outLength] = 0;
在第一行中,您分配 outLength
个字节,但是在第二行中,您将写到比缓冲区末尾多一个字节的位置.取决于页面边界和 malloc
中其他神秘事件的发生,可能是正确的,也可能不是.那可以解释为什么它不会每次崩溃.
In the first line you allocate outLength
bytes, but in the second line you write to a position one byte beyond the end of the buffer. Depending on page boundaries and other mysterious happenings inside malloc
, that might be OK or it might not. That would explain why it doesn't crash every time.
尝试以下方法:
char *outputBuffer = malloc(outLength + 1);
outputBuffer[outLength] = 0;
这可能会解决您的问题.
That might fix your problem.
这篇关于为什么此Objective-C代码会引发malloc错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!