C++ memcpy和快乐访问冲突

Mar*_*ger 2 c++ memcpy access-violation

由于某种原因,我无法想象我正在获得访问权限.

memcpy_s (buffer, bytes_per_line * height, image, bytes_per_line * height);
Run Code Online (Sandbox Code Playgroud)

这是完整的功能:

int Flip_Bitmap(UCHAR *image, int bytes_per_line, int height)   
{   
    // this function is used to flip bottom-up .BMP images   

    UCHAR *buffer; // used to perform the image processing   
    int index;     // looping index   

    // allocate the temporary buffer   
    if (!(buffer = (UCHAR *) malloc (bytes_per_line * height)))   
        return(0);   

    // copy image to work area   
    //memcpy(buffer, image, bytes_per_line * height);   
    memcpy_s (buffer, bytes_per_line * height, image, bytes_per_line * height);

    // flip vertically   
    for (index = 0; index < height; index++)   
        memcpy(&image[((height - 1) - index) * bytes_per_line], &buffer[index * bytes_per_line], bytes_per_line);   

    // release the memory   
    free(buffer);   

    // return success   
    return(1);   

} // end Flip_Bitmap   
Run Code Online (Sandbox Code Playgroud)

整个代码:http: //pastebin.com/udRqgCfU

要运行它,您需要在源目录中使用24位位图.这是一个更大的代码的一部分,我试图使Load_Bitmap_File功能工作......所以,任何想法?

Ada*_*eld 5

您正在获得访问冲突,因为许多图像程序设置不biSizeImage正确.您正在使用的图像可能已biSizeImage设置为0,因此您不会为图像数据分配任何内存(实际上,您可能正在分配4-16个字节,因为大多数malloc实现将返回非NULL值,即使请求的分配大小为0).因此,当您复制数据时,您正在读取该数组的末尾,这会导致访问冲突.

忽略biSizeImage参数并自己计算图像大小.请记住,每条扫描线的大小必须是4个字节的倍数,因此您需要向上舍入:

// Pseudocode
#define ROUNDUP(value, power_of_2) (((value) + (power_of_2) - 1) & (~((power_of_2) - 1)))
bytes_per_line = ROUNDUP(width * bits_per_pixel/8, 4)
image_size = bytes_per_line * height;
Run Code Online (Sandbox Code Playgroud)

然后只需使用相同的图像大小读取图像数据并翻转它.