Segmentation fault when calling "new" in c++?
Solution 1
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.
Solution 2
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);
Related videos on Youtube
Comments
-
Shang Wang almost 2 years
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 2Intervals
. 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.
-
Oliver CharlesworthWhen does the segfault occur? Please show us the code for
Box
. -
hmakholm left over Monica@Moo,
new
can conceivably segfault if there is heap corruption.
-
-
thiton over 12 yearsAnd don't forget to put an fflush() in this sequence, or else error messages might end up in an unwritten buffer. Even better, use a debugger.