For some reason, the following program crashes before “i got here” is printed. When I comment out the try-catch part, the program runs and exits normally.
#include <iostream>
int error_function () {
throw 5;
return 0;
}
int main () {
double* b = new double[6];
for (int i = 0; i < 6; i++) {
b[i] = i;
}
double* c = new double(*b);
for (int i = 0; i < 6; i++) {
c[i] = i+1;
}
for (int i = 0; i < 6; i++) {
std::cout << b[i] << " " << c[i] << std::endl;
}
try {
error_function();
}
catch (int t) {
std::cout << "catched an int: " << t << std::endl;
}
std::cout << "i got here" << std::endl;
return 0;
}
This is the entire output I get when the program crashes:
0 1
1 2
2 3
3 4
4 5
5 6
catched an int: 5
*** glibc detected *** ./main: free(): invalid next size (fast): 0x0000000001f22070 ***
======= Backtrace: =========
/lib/libc.so.6(+0x77806)[0x7f2b273a0806]
/lib/libc.so.6(cfree+0x73)[0x7f2b273a70d3]
./main[0x400d92]
(a bunch of stuff)
Aborted
I have no idea why this is happening. Any help would be greatly appreciated!
It’s crashing because you’ve only allocated one double when you allocate c and then proceed to overrun the bounds by accessing elements after the first. It looks as if in this case after the exception has been handled there is some cleanup and the glibc has detected corrupt memory.
The problem lines are these:
It allocates a new double that copies the value of *b (or b[0] if you like) because b is just a pointer so dereferencing it does not invoke the copy constructor that copies an array.
You would be better off using a std::vector as it would automatically take care of any memory allocation and deallocation for you as well as being exception safe. In the case your
error_functionthrew an exception that you did not handle it would still clean up correctly, whereas yournew‘d memory does not as it stands.Technically it’s undefined behaviour, so anything could happen.