0
您好我使用base 64編碼爲我的字符串,但我有時崩潰。它不是經常複製。我嘗試了不同的方式,但沒有取得成功。崩潰的基地64編碼
這裏是崩潰:
的malloc:*錯誤對象0x6880830:不正確的校驗和釋放對象 - 對象被釋放後,可能被修改。 *設置malloc_error_break斷點調試
這裏是代碼片段:
-(NSString *)Base64Encode:(NSData *)data{
if([data length])
{
//Point to start of the data and set buffer sizes
int inLength = [data length];
int outLength = ((((inLength * 4)/3)/4)*4) + (((inLength * 4)/3)%4 ? 4 : 0);
const char *inputBuffer = [data bytes];
char *outputBuffer = malloc(outLength);
outputBuffer[outLength] = 0;
//64 digit code
static char Encode[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/";
//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] = '=';
/*
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;
}
else {
return @"";
}
}
這段Base64Encode代碼像轉發郵件一樣在互聯網上傳播。我的同事程序員曾經使用過這些代碼,並且在不知道它包含這樣的缺陷的情況下使用它,並且我們的應用程序一直在崩潰,直到我看看它。 – tia 2012-02-19 11:07:07
@Sven Thanx很多! – iPamu 2012-02-19 11:31:53
絕對正確。它幫助了我。 – Nitish 2012-04-05 08:53:51