C++ memcpy 和愉快的访问冲突

标签 c++ access-violation memcpy

出于某种原因,我无法确定我遇到了访问冲突。

memcpy_s (buffer, bytes_per_line * height, image, bytes_per_line * height);

这是整个函数:

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   

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

要运行它,您需要源目录中的 24 位位图。 这是更大代码的一部分,我正在尝试使 Load_Bitmap_File 函数工作... 那么,有什么想法吗?

最佳答案

您遇到访问冲突是因为很 multimap 像程序没有正确设置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;

然后只需使用相同的图像大小来读取图像数据并进行翻转。

关于C++ memcpy 和愉快的访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6846971/

相关文章:

C++/SDL : vector/surface issues

c++ - 卸载时XAudio2访问冲突异常

c++ - C++ 中 sizeof 的行为

c - 如何在 C 中修复 "free(): invalid next size (normal) | Canceled (memory dump written)"

c++ - Linux 上的 memcpy 性能不佳

c++ - 可以推断左值引用非类型模板参数吗?

c++ - 为什么 long long 不是 int64_t 但它们具有相同的大小?

c++ - 赋值运算符重载和无效内存

c++ - 访问 void * 的元素?

c++ - 为什么 string::find 返回 size_type 而不是迭代器?