Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vala memory management

I am going to call a Vala function from C, and I have a question about memory management. The function looks like this in Vala:

int[] GetNumbers();

and is translated by valac to C like this

gint* GetNumbers(int* result_length1);

When the above function gets called from C, is the caller responsible for freeing the gint* array?

like image 695
D R Avatar asked Jun 12 '10 21:06

D R


1 Answers

A Vala question! How cool!

Vala has a useful -C option that allows you to take a peek at the C-code it generates. This function, for example...

int[] GetNumbers() {
    return new int[] {1,2,3};
}

...when compiled with...

valac -C -c test.vala

...will reveal the following C-code (in test.c)...

gint* GetNumbers (int* result_length1) {
    gint* result = NULL;
    gint* _tmp0_ = NULL;
    gint* _tmp1_;
    result = (_tmp1_ = (_tmp0_ = g_new0 (gint, 3), _tmp0_[0] = 1, _tmp0_[1] = 2, _tmp0_[2] = 3, _tmp0_), *result_length1 = 3, _tmp1_);
    return result;
}

Note the g_new0; so yes, you want to g_free it.

Even if you're just going by the header file, and can't be bothered to look at every implementation, it looks like the same rules apply as in C: if it ain't const, free it.

like image 87
Stéphan Kochen Avatar answered Oct 07 '22 01:10

Stéphan Kochen