开发者

Segmentation fault when calling "new" in c++?

I got segfault when tryi开发者_运维问答ng to call "new" to create a pointer and push it into a vector. The code that I push the element in the vector is:

queue->push_back(new Box(gen_id, Interval(x_mid, x_end), Interval(y_mid-y_halfwidth, y_mid+y_halfwidth)));

Basically Box is a Class and the constructor just take 3 arguments, generation_id, and 2 Intervals. I printed out the content in vector before and after this "push", before:

[ -0.30908203125, -0.3087158203125 ] , [ -0.951416015625, -0.9510498046875 ]
[ -0.3087158203125, -0.308349609375 ] , [ -0.951416015625, -0.9510498046875 ]
[ -0.30908203125, -0.3087158203125 ] , [ -0.9510498046875, -0.95068359375 ]
[ -0.3087158203125, -0.308349609375 ] , [ -0.9510498046875, -0.95068359375 ]

after:

[ -0.30908203125, -0.3087158203125 ] , [ -0.951416015625, -0.9510498046875 ]
[ -0.3087158203125, -0.308349609375 ] , [ -0.951416015625, -0.9510498046875 ]
[ 8.9039208750109844342e-243, 6.7903818933216500424e-173 ] , [ -0.9510498046875, -0.95068359375 ]
[ -0.3087158203125, -0.308349609375 ] , [ -0.9510498046875, -0.95068359375 ]
[ -0.3087158203125, -0.308349609375 ] , [ -0.95123291015625, -0.95086669921875 ]

I have no clue why does this happen, but apparently, there's one element got corrupted. There's no other codes between these two sets of output except that "push", and I used gdb to confirm that. Also, I checked those 2 Intervals variables, both give me a result that make sense.

My questions is: in what situation does "new" get segfault? Or is my problem caused because of other stuff? Thanks.


Assuming it really is new generating the segfault, the most common cause would be a corrupted heap, typically a result of overwriting memory you don't own and/or a double delete.

Valgrind will be your friend if you can run on a Linux system.


I doubt that new itself is giving you the segfault; the problem is probably in one of the constructors. Try splitting up that giant line, and put in some print statements to see exactly where the problem is.

printf("Creating the first interval...\n");
Interval a(x_mid, x_end);
printf("Creating the second interval...\n");
Interval b(y_mid-y_halfwidth, y_mid + y_halfwidth);
printf("Creating the box...\n");
Box* box_to_enqueue = new Box(gen_id, a, b);
printf("Enqueueing the box...\n");
// Do you really want to enqueue a pointer instead of a Box?
queue->push_back(box_to_enqueue);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜