Opencv and memory issues

asked Oct 2 '14

Nikos gravatar image

updated Oct 2 '14

int a*;

a = malloc(3*sizeof(int));
a[0]=1; a[1]=2; a[2]=3;
M = cv::Mat(3,1,CV_32S , a);

cout<< "correct answer:"<<endl;
cout << M << endl;
free(a);
cout<<"problem:"<<endl;

cout<<M<<endl;

This program results to:

correct answer:
[1;
2;
3]
problem:
[4;
0;
 24411984]

WHY??????`

Preview: (hide)

Comments

Replace a by a.clone() when creating M and i am guessing it should be fixed. Basically freeing OpenCV smart pointers is not thar smart. The clone makes sure you no longer link the data of a and M

StevenPuttemans gravatar imageStevenPuttemans (Oct 2 '14)edit
1

I think StevenPuttemans is right, that should solve it. But I want to add that the code you posted is very bad. Why are you using free and malloc in a c++ program!? Why are you even allocating it dynamically? To discover why your problem occured read this

boaz001 gravatar imageboaz001 (Oct 2 '14)edit

Like boaz said, C++ and memory allocation are a very weird combination. C++ does it all for you!

StevenPuttemans gravatar imageStevenPuttemans (Oct 3 '14)edit