Search code examples
c++segmentation-faultnew-operatorallocation

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


I got segfault when trying 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.


Solution

  • 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.