Take the 2-minute tour ×

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));


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.


Saurabh Gandhi

share|improve this question
add comment

1 Answer

up vote 6 down vote accepted

You're not allocating enough memory, this:


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.

share|improve this answer
Gosh...I now realize the stupidity of my question and what i was missing...you still made my sunday...Thanks a lot!! –  Saurabh Gandhi Jul 10 '11 at 6:57
umm And don't cast the return value from malloc unless you are forced to, by compiler :) Bill Gates says: error C2440: 'initializing' : cannot convert from 'void ' to 'char *' 1> Conversion from 'void' to pointer to non-'void' requires an explicit cast –  Ulterior Jul 10 '11 at 10:40
@user757808: "'void' to 'char *'" or "'void *' to 'char *'"? The first one means that you're missing a header, the second means that your compiler is broken (or in C++ mode) as you don't need an explicit cast from void* to any other non-function pointer type in C. –  mu is too short Jul 10 '11 at 18:58
@mu is too short as usual, StackOverflow mangled with my response. –  Ulterior Jul 10 '11 at 21:34
add comment

Your Answer


