尝试为映像缓冲区分配内存时,ptr值不正确

时间:2017-01-18 22:22:11

标签: c++ opencv pointers cuda

unsigned char* createImageBuffer(unsigned int bytes)
{
    unsigned char* ptr;
    cudaSetDeviceFlags(cudaDeviceMapHost);
    cudaHostAlloc(&ptr, bytes, cudaHostAllocMapped);    
    return ptr;
}


    cv::Mat sGray(frame.size(), CV_8U, createImageBuffer(frame.size().width * frame.size().height));

    cv::Mat dGray(frame.size(), CV_8U, createImageBuffer(frame.size().width * frame.size().height));

    cv::Mat eGray(frame.size(), CV_8U, createImageBuffer(frame.size().width * frame.size().height));

调试期间的问题是访问0x00000000处的受限内存。该函数应该返回一个指向图像字节分配位置的指针,但是它给了我糟糕的ptr值。

输出:

  

improc.exe中0x0c10e473处的第一次机会异常:0xC0000005:Access   违规读取位置0x00000000。处理未处理的异常   improc.exe中的0x0c10e473:0xC0000005:访问冲突读取   位置0x00000000。

我遵循的教程视频:https://youtu.be/j9vb5UjQCQg

1 个答案:

答案 0 :(得分:1)

API可能无法分配足够的内存。检查cudaHostAlloc的返回值(参见doku on cudaHostAlloc):

unsigned char* createImageBuffer(unsigned int bytes)
{
    unsigned char* ptr;
    cudaSetDeviceFlags(cudaDeviceMapHost);
    cudaError_t allocResult = cudaHostAlloc(&ptr, bytes, cudaHostAllocMapped);
    if (allocResult != cudaSuccess) {
      // could be cudaErrorMemoryAllocation; The API call failed because
      // it was unable to allocate enough memory to perform
      // the requested operation.
      return nullptr;
    }
    return ptr;
}