避免.oct函数中的分段错误?

时间:2017-04-14 12:43:08

标签: c++ octave

这主要针对Octave的用户。

在Octave的c ++ API文档中,其中一个示例是一个添加两个矩阵的函数,如下所示:

*/addtwomatrices.cc
#include <octave/oct.h>
DEFUN_DLD (addtwomatrices, args, , "Add A to B")
{
  if (args.length () != 2)
    print_usage ();

  NDArray A = args(0).array_value ();
  NDArray B = args(1).array_value ();

 return octave_value (A + B);
}

链接:https://www.gnu.org/software/octave/doc/interpreter/Matrices-and-Arrays-in-Oct_002dFiles.html#Matrices-and-Arrays-in-Oct_002dFiles

工作正常,编译没有错误。 但是在Octave中使用它时,如果使用不正确数量的参数调用函数,则会出现故障并退出程序并转储八度核心。

即使使用不正确数量的参数调用此函数,有没有办法保持八度音程打开? 例如,

addtwomatrices(5)
octave 1> "Incorrect Number of Arguments Supplied. Please provide 2."
octave 2>'

而不是

Invalid call to addtwomatrices.  Correct usage is:

Adds 2 matrices
Additional help for built-in functions and operators is
available in the on-line version of the manual.  Use the command
`doc <topic>' to search the manual index.

Help and information about Octave is also available on the WWW
at http://www.octave.org and via the help@octave.org
mailing list.
panic: Segmentation fault -- stopping myself...
attempting to save variables to `octave-core'...
save to `octave-core' complete
Segmentation fault

1 个答案:

答案 0 :(得分:3)

您正在阅读Octave(4.2.1)最新版本的在线手册,但您没有使用Octave 4.2.1。您需要查看Octave版本的文档:

如果您使用的是Octave 4.2.X版本,那么它的行为将如您所愿:

$ cat addtwomatrices.cc 
#include <octave/oct.h>
DEFUN_DLD (addtwomatrices, args, , "Add A to B")
{
  if (args.length () != 2)
    print_usage ();

  NDArray A = args(0).array_value ();
  NDArray B = args(1).array_value ();

 return octave_value (A + B);
}
$ mkoctfile-4.2.1 addtwomatrices.cc 
$ octave-cli-4.2.1 -q
octave-cli-4.2.1:1> addtwomatrices (5)
error: Invalid call to addtwomatrices.  Correct usage is:

Add A to B
octave-cli-4.2.1:1>
$ mkoctfile-4.0.0 addtwomatrices.cc 
$ octave-cli-4.0.0 -q
octave-cli-4.0.0:1> addtwomatrices (5)
error: Invalid call to addtwomatrices.  Correct usage is:

Add A to B
panic: Segmentation fault -- stopping myself...
Segmentation fault

在Octave的libinterp中处理错误的方式在4.2中有所改变。如果您使用的是旧版本,则需要自行处理函数的返回。你应该这样做:

#include <octave/oct.h>
DEFUN_DLD (addtwomatrices, args, , "Add A to B")
{
  if (args.length () != 2)
    {
      print_usage ();
      // In octave 4.2, print_usage also throws exceptions
      // and exist the function.  This is the same behaviour
      // in Octave m language.  In Octave 4.0, it only prints
      // the usage and then you still need to return otherwise
      // it continues execution of the function.
      return octave_value (); 
    }

  NDArray A = args(0).array_value ();
  NDArray B = args(1).array_value ();

 return octave_value (A + B);
}