gpt4 book ai didi

c - 显然我正在破坏堆栈——但是如何呢?

转载 作者:太空狗 更新时间:2023-10-29 17:09:31 25 4
gpt4 key购买 nike

我有一个非常简单的程序,如下所列,它从 .mat 文件(来自 Matlab 的数据文件)中读取一个值并打印它。出于某种原因,退出 main() 后出现段错误 - 我可以运行 gdb my_program 并单步执行整个方法,但是 main( ) 完成后,我在 Matlab 相关库(libmwfl.solibmat.so 的依赖项)中输入了一些方法,这会引发段错误。

我对 C 编程完全陌生,但一些阅读我怀疑我不知何故 corrupting the stackcalling some destructor twice .但是,我在我的代码中看不到任何这些 - 正如我所说,我可以毫无问题地使用调试器单步执行我的代码。

我在这里做错了什么?

#include <stdlib.h>
#include <stdio.h>
#include <mat.h>

int main(int argc, char *argv[]) {

double value;
MATFile *datafile;
datafile = matOpen("test.mat", "r");

mxArray *mxv;
mxv = matGetVariable(datafile, "value");
value = *mxGetPr(mxv);
mxFree(mxv);
matClose(datafile);

printf("The value fetched from the .mat file was: %f", value);

return 0;
}

最佳答案

文档推荐使用函数mxDestroyArray而不是 mxFree免费 mxArray .通过使用 mxFree你可能搞砸了 matlab 的堆。来自documentation

Improperly Destroying an mxArray

You cannot use mxFree to destroy an mxArray.

Warning: You are attempting to call mxFree on a <class-id> array. The destructor for mxArrays is mxDestroyArray; please call this instead. MATLAB will attempt to fix the problem and continue, but this will result in memory faults in future releases.

Example That Causes Warning

In the following example, mxFree does not destroy the array object. This operation frees the structure header associated with the array, but MATLAB will still operate as if the array object needs to be destroyed. Thus MATLAB will try to destroy the array object, and in the process, attempt to free its structure header again.

mxArray *temp = mxCreateDoubleMatrix(1,1,mxREAL);

  ...

mxFree(temp); /* INCORRECT */

Solution.

Call mxDestroyArray instead.

mxDestroyArray(temp); /* CORRECT */

关于c - 显然我正在破坏堆栈——但是如何呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12215026/

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