Saurabh Gandhi
Saurabh Gandhi

Reputation: 361

Heap corruption while using OpenCV datastructure

I am using OpenCV 2.1 with codeblocks (gcc under mingw). Within my code I am trying (for some sane reason) to access the imagedata within IplImage datastructure directly. Kindly refer the code snippet for more details:

int main(void)
{
    IplImage* test_image = cvLoadImage("test_image.bmp",CV_LOAD_IMAGE_GRAYSCALE);
    int mysize = test_image->height * test_image->widthStep;
    char* imagedata_ptr = NULL;

    int i   =   0;    
    imagedata_ptr = test_image->imageData;

    char* temp_buff = (char *)malloc(sizeof(mysize));
    memcpy(temp_buff,imagedata_ptr,mysize);

    free(temp_buff);
}

When I run this code it crashes. On running it in the debug mode it generates a SIGTRAP is due to heap corruption. At first I suspected that this might be a compiler related issue and hence tried running the same code in Visual Studio. But it still crashes. Thats the reason I feel it could be an OpenCV related issue.

NOTE: There are no other instances of program open, this is the only code that I am running, no threading etc is being done here.

Awaiting your comments on the same.

Regards,

Saurabh Gandhi

Upvotes: 1

Views: 809

Answers (1)

mu is too short
mu is too short

Reputation: 434985

You're not allocating enough memory, this:

char* temp_buff = (char *)malloc(sizeof(mysize))

only allocates sizeof(int) bytes (probably 4) and that's probably a lot less than you need. Then the memcpy right after that will copy test_image->height * test_image->widthStep bytes of data into somewhere that only has space for sizeof(int) bytes and you have now scribbled all over your memory and corrupted your heap.

I'd guess that you really want to say this:

char *temp_buff = malloc(mysize);

And don't cast the return value from malloc, you don't need it and it can hide problems.

Upvotes: 6

Related Questions