Lee Torres
Lee Torres

Reputation: 561

Releasing data from a char* in C++

I'm pulling data from a uEye industrial camera, and am retrieving images through the camera's API.

My code looks something like this:

bool get_image(char*& img)
{
    void *pMemVoid; //pointer to where the image is stored

// Takes an image from the camera. If successful, returns true, otherwise
// returns false
    if (is_GetImageMem(hCam, &pMemVoid) == IS_SUCCESS){

        img = (char*) pMemVoid;
        pMemVoid = NULL;
        return true;
    }
    else
        return false;
}

I'm retrieving a image data, and if it is successful, it returns true, otherwise returns false.

The problem is I believe I'm leaking memory with img = (char*) pMemVoid, because I'm repeatedly calling this function and not releasing this data. How do I release the memory that is assigned to img?

EDIT:

I'm initializing the camera in a function that uses is_AllocImageMem:

// Global variables for camera functions
HIDS hCam = 0;
char* ppcImgMem;
int pid;

/* Initializes the uEye camera. If camera initialization is successful, it
 * returns true, otherwise returns false */
bool init_camera()
{
  int nRet = is_InitCamera (&hCam, NULL);

  is_AllocImageMem(hCam,752, 480, 1 ,&ppcImgMem, &pid);  
  is_SetImageMem(hCam, ppcImgMem, pid);
  is_SetDisplayMode (hCam, IS_SET_DM_DIB);
  is_SetColorMode (hCam, IS_CM_MONO8);
  int pnCol , pnColMode;
  is_GetColorDepth(hCam, &pnCol , &pnColMode);

  is_CaptureVideo(hCam, IS_WAIT);

  if (nRet != IS_SUCCESS)
    {
      if (nRet == IS_STARTER_FW_UPLOAD_NEEDED)
      {
        hCam = hCam | IS_ALLOW_STARTER_FW_UPLOAD;
        nRet = is_InitCamera (&hCam, NULL);
      }
      cout << "camera failed to initialize " << endl;
      return false;
    }
  else
    return true;
}

Upvotes: 1

Views: 825

Answers (2)

Lee Torres
Lee Torres

Reputation: 561

I ran valgrind on the code, the output had roughly 16,000,000 bytes possibly lost, and roughly 20,000,000 bytes indirectly lost.

When the image was retrieved from get_image and assigned to img, img was assigned as data to an OpenCV IplImage like this:

  IplImage* src = cvCreateImage(cvSize(752,480), IPL_DEPTH_8U, 1);
  src -> imageData = img;

The IplImage was being retained, so I had to call cvReleaseImage on the IplImage stored in memory. Now valgrind reports that indirectly lost are at 0, and possibly lost at about 1,600,000. Still havn't accounted for the 1.6 million, but I think the IplImage contributed significantly to the memory leak

Upvotes: 0

Bill Carey
Bill Carey

Reputation: 1415

The API Documentation seems to suggest that there's a corresponding is_FreeImageMem function. Have you tried that?

Edit: It looks like is_GetImageMem may not allocate memory. From its description:

is_GetImageMem() returns the starting address of the image memory last used for image capturing.

Are you calling is_AllocImageMem anywhere?

Upvotes: 3

Related Questions