开发者

deallocating gsl vectors in structs

开发者 https://www.devze.com 2023-01-29 05:46 出处:网络
Can you explain what\'s going on with my code here? I\'m not sure if I\'m using the destructor correctly or not in the struct.

Can you explain what's going on with my code here? I'm not sure if I'm using the destructor correctly or not in the struct.

With the destructor in there I get:

function1: 23

function2: 8.86183e-317

* glibc detected ./a: double free or corruption (fasttop): 0x000000000111b010 **

If I just comment out the destructor I get:

function1: 23

function2: 24

which is what I want. But don't I need the destructor to avoid a memory leak for a more complicated program?

(As you can see I may be a bit confused on pointers/allocation in general)

Thanks!

Edit: oh yeah, and why does the extra allocation step in function1 make a difference?

Edit2: Should I be initializing x = 0 in the constructor? I thought that was proper...should I be allocating it on initialization when I do this? So instead: 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_开发者_JAVA百科get(s.x, 0) << endl;

    return 0;
}


Inside of function1 and function2 you make a copy of the struct1 object that you create in the main() function. These copies have the same pointer x. When the destructor for each of these copies is called, gsl_vector_free is called, so you try to call it three times on the same pointer:

  • once in function1 when s is destroyed
  • once in function2 when s is destroyed
  • once in main when s is destroyed

You need to implement a copy constructor and copy assignment operator for this class. Any time you have a class that owns a resource, you need to implement these two functions and a destructor. A resource is anything that needs to be cleaned up when you are done using it.

In your sample code, it would be far better to encapsulate all of the allocation and deallocation inside of the class so that you can use the class without worrying about it. Make the class actually manage its resource.

0

精彩评论

暂无评论...
验证码 换一张
取 消