gpt4 book ai didi

c++ - 避免 .oct 函数中的段错误?

转载 作者:行者123 更新时间:2023-11-27 23:54:43 24 4
gpt4 key购买 nike

这主要针对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 中使用它时,如果使用错误数量的参数调用该函数,它会出现错误并退出程序并转储 octave-core。

即使使用错误数量的参数调用此函数,是否有办法保持 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

最佳答案

您正在阅读最新版 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);
}

关于c++ - 避免 .oct 函数中的段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43411752/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com