Ask Your Question
0

Seg fault comes when trying to access Mat through Dynamic Memory allocation

asked 2015-09-10 09:49:30 -0600

sarjoondeen gravatar image

In my application I am doing something like declaring a Mat variable inside a Structure in my main.h file like

struct image_proc { Mat image; };

In my main.cpp function I declared a pointer object for that structure and allocate dynamic memory for that

struct image_proc *obj;

int main() { obj = (struct image_proc )malloc(sizeof(struct image_proc)) /Calling a function "processing with the structure handle" */ processing(obj); }

void processing(struct image_proc handle) { / Trying to access image variable for some operations / handle->image = /operation*/ -> Seg fault comes when I try to access this variable "image"

}

Why I am getting core dump when I try to access the image through pointer I cannot access the image when I do dynamic memory allocation

But when I do static memory allocation. I can able to access the variable and can I do whatever I want to do with that Why its only failing If i do dynamic allocations.

I know that Mat will do automatic memory allocation and de-allocation. I want to pass that through structure and experiment but its getting failed

Please help me with this.

Regards, Sarjoondeen.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
2

answered 2015-09-10 10:16:37 -0600

berak gravatar image

updated 2015-09-10 13:55:32 -0600

  • no, you can't malloc() a cv::Mat, it's a complex c++ class, that relies on its constructor being called properly, and you're not doing that.

  • new/delete would be a different story, but please, try to avoid that, too. (along with all unnessecary manual memory management, and also raw pointers in general).

  • prefer auto storage, and use vector<Mat> and such, this is c++, not C !

  • again, please reconsider your general design with this.

edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2015-09-10 09:45:40 -0600

Seen: 720 times

Last updated: Sep 10 '15