malloc失败

来源:互联网 发布:女仆聊天软件 编辑:程序博客网 时间:2024/04/28 06:33

     今天遇到了一个问题,malloc失败,下边是其中的一部分代码,在一个循环中:

 

if(cinfo->num_components == 1)
   {
    unsigned char* tmpBuf=(unsigned char* )malloc(cinfo->output_width*nPixelSize);
   
    for(int k=0;k < cinfo->output_width;k++)
    {
     tmpBuf[3*k] = buff[k];
     tmpBuf[3*k+1] = buff[k];
     tmpBuf[3*k+2] = buff[k];
    }
    memcpy(buff,tmpBuf,bmp_line_length);
    free(tmpBuf);
   }
   memcpy(aSrc->m_bitBuf, aSrc->m_bitBuf+bmp_line_length, bmp_line_length);
   memcpy(aSrc->m_bitBuf+bmp_line_length, buff, bmp_line_length);

 

其中aSrc->m_bitBuf 为前面其他函数中申请的,大小为10240,在malloc失败的例子中bmp_line_length的大小为6359,问题就出在上边代码的最后一句,由于6359*2>10240,所以memcpy越界,所以当第2次循环到malloc的时候就申请内存失败了,而这时候内存还足够呢,所以又收获了一点,当有内存越界操作时可能申请内存失败。随后又在网上查了下,别人已经提到过类似的问题:

#include <stdlib.h>
#include 
<stdio.h>
#include 
<memory.h>

int main()
{
    #define BUF_SIZE 25

    _asm 
int 3;
    
char* lpszBuf = (char*)malloc(BUF_SIZE);
    memset(lpszBuf, 
0x00, BUF_SIZE*2);
    
char* lpszTest = (char*)malloc(BUF_SIZE); // <==== 内存分配失败
    free(lpszBuf);                            // <==== 出错 执行到 int 3; 指令
    free(lpszTest);

    
return 0;
}