你能解释一下我的代码在这里发生了什么吗?我不确定我是否在结构中正确使用了析构函数。
有了析构函数,我得到:
function1: 23
function2: 8.86183e-317
* glibc detected./a:双重释放或损坏(fasttop):0x000000000111b010 * *
如果我只是注释掉我得到的析构函数:
function1: 23
function2: 24
这就是我想要的。但是我不需要析构函数来避免更复杂程序的内存泄漏吗?
(如您所见,我可能对一般的指针/分配有点困惑)
谢谢!
编辑:哦,是的,为什么function1中的额外分配步骤会有所不同?
Edit2:我应该在构造函数中初始化 x = 0 吗?我认为这是正确的......当我这样做时,我应该在初始化时分配它吗?所以改为:x = gsl_vector_alloc(1)。
#include <iostream>
using namespace std;
#include <cassert>
#include <cmath>
#include <gsl/gsl_vector.h>
struct struct1{
gsl_vector * x;
struct1() {
x = 0;
}
~struct1() {
if (x) gsl_vector_free(x);
}
};
void function1(void *p) {
struct1 s = *(struct1 *) p;
s.x = gsl_vector_alloc(1);
gsl_vector_set(s.x, 0, 24);
}
void function2(void *p) {
struct1 s = *(struct1 *) p;
gsl_vector_set(s.x, 0, 24);
}
int main() {
struct1 s;
s.x = gsl_vector_alloc(1);
gsl_vector_set(s.x, 0, 23);
function1(&s);
cout << "function1: " << gsl_vector_get(s.x, 0) << endl;
function2(&s);
cout << "function2: " << gsl_vector_get(s.x, 0) << endl;
return 0;
}