您能解釋我的代碼在這裏發生了什麼嗎?我不確定是否正確使用析構函數或不在結構中。在結構中釋放gsl向量
隨着析構函數在那裏我得到:
功能1:23
功能2:8.86183e-317
* glibc的檢測 ./a:雙重釋放或腐敗(fasttop):0x000000000111b010 * *
如果我只是註釋掉析構函數,我得到:
功能1:23
功能2: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;
}
你爲什麼使用`void *`? – 2010-12-03 18:15:51