ここで自分のコードで何が起こっているのか説明できますか?構造体にデストラクタを正しく使用しているのかどうかはわかりません。そこでのデストラクタで構造体のgslベクトルの割り当て解除
私が取得:
はfunction1:23
機能2:8.86183e-317
*のglibcが検出 ./a:ダブル無料または破損(fasttop):0x000000000111b010 * *
私が取得:
はfunction1: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 * 'を使用していますか? –