【问题标题】:Crash for Base 64 encodingBase 64 编码崩溃
【发布时间】:2012-02-19 10:44:41
【问题描述】:

您好,我正在为我的字符串使用 base 64 编码,但有时我会崩溃。它不经常复制。我尝试使用不同的方法,但没有成功。

这里是崩溃:

malloc: * 对象 0x6880830 错误:已释放对象的校验和不正确 - 对象可能在被释放后被修改。 * 在 malloc_error_break 中设置断点进行调试

这里是代码 sn-p:

-(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[] = "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] = '=';

/* 
 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 @"";
}

}

【问题讨论】:

    标签: iphone objective-c


    【解决方案1】:

    您正在写入超出输出缓冲区的末尾:

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

    如果你分配outLength + 1 字节你应该没问题。

    【讨论】:

    • 这段Base64Encode代码像转发邮件一样在互联网上流传。我的程序员同事曾经拿过这段代码并在不知道它包含这样的缺陷的情况下使用它,并且我们的应用程序一直在崩溃,直到我查看它为止。
    猜你喜欢
    • 1970-01-01
    • 2011-04-03
    • 1970-01-01
    • 2014-11-30
    • 2011-10-11
    • 1970-01-01
    • 2018-09-01
    • 2012-12-15
    • 2019-02-16
    相关资源
    最近更新 更多