I discovered the issue while writing a longer and more complex program (FEM Solver), but to troubleshoot it I started to remove code until I had this simple example that crashes in the same way.
The following .oct file crashes in about 1 in 4 times, but it is random and sometimes it can run for 50 times without crashing. When it crashes it closes Octave without warnings, hence I have not been able to debug it. (The larger code I have with many more variables crashes about 80 % of the time).
I have tried this in both Octave 5.1.0 and 5.1.1 (unofficial) for Windows 10 x64, and on at least one other computer. It also doesn't matter if i run Octave in CLI or GUI mode.
I'm hoping I have made some simple mistake... but I can't seem to find it.
.m script to check when it crashes:
for i = 1:50
a = test7(5)
end
test7.cc file that is compiled to .oct:
#include <octave/oct.h>
DEFUN_DLD (test7, args, nargout,
"Test code that crashes...")
{
if (args.length () != 1) {
print_usage ();
return octave_value();
}
const int N = args(0).int_value();
const int savesTot = 500000;
int iter = 0;
//Declaration method 1 (also crashes)
//OCTAVE_LOCAL_BUFFER (double, Q, N);
//Declaration method 2 (also crashes)
//double *Q = new double(N);
//Declaration method 3 (crashes)
NDArray Q_o (dim_vector (N,1));
double *Q = Q_o.fortran_vec();
//Q_o(0) = 1.1; // Calling NDArray class (also crashes)
Q[0] = 1.1; // Calling pointer to raw data directly (faster)
while (iter < savesTot) {
for (int i = 0; i<N; i++) {
if (i == 0) {
//Q_o(i+1) = 1.0;
Q[i+1] = 1.0;
} else if ( i == (N-1) ) {
//Q_o(i+1) = 2.0;
Q[i+1] = 2.0;
} else {
//Q_o(i+1) = 3.0;
Q[i+1] = 3.0;
}
}
iter++;
OCTAVE_QUIT; // Check if user has pressed Ctrl+C
}
octave_value_list retval; // Define return list (can contain many variables)
retval(0) = iter;
if (! error_state) { return retval; }
return octave_value_list ();
}
test7.cc is compiled to test7.oct inside Octave 5.1.1 or 5.1.0 on Windows 10 x64 with the following command:
mkoctfile test7.cc
Your problem is that you write out of bounds:
for (int i = 0; i<N; i++) {
//...
Q[i+1] = 3.0;
//...
}
You might want to loop i=1; i<N; i++
and index Q[i]
, or loop i=0; i<N-1; i++
.