Opencv and memory issues

asked 2014-10-02 15:37:11 -0600

Nikos gravatar image

updated 2014-10-02 15:42:12 -0600

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??????`

edit retag flag offensive close merge delete

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 ( 2014-10-02 15:45:37 -0600 )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 ( 2014-10-02 16:32:23 -0600 )edit

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

StevenPuttemans gravatar imageStevenPuttemans ( 2014-10-03 02:57:16 -0600 )edit