[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[igraph] confused about vector pointer memory management

From: Szabolcs Horvát
Subject: [igraph] confused about vector pointer memory management
Date: Wed, 3 May 2017 13:59:12 +0200


I am a bit confused about the correct usage of these functions:


In particular, I do not understand why igraph_vector_ptr_destroy_all()
will both destroy and free all items, but igraph_vector_ptr_clear()
will destroy them without freeing.

It seems to me that igraph_vector_ptr_clear() should either not call
element destructors at all, or it should both free and destroy
elements, like igraph_vector_ptr_destroy_all() does.

Here's why.

Consider the following situation:

igraph_vector_ptr_t res;
igraph_vector_ptr_init(&res, 0);

IGRAPH_VECTOR_PTR_SET_ITEM_DESTRUCTOR(&res, igraph_vector_destroy);

This data structure is essentially a vector of vectors.  There is an
element destructor set.

Now suppose that we add some elements to this vector_ptr, e.g. by
igraph_vector_ptr_push_back().  To add an element, which will be a
vector, first we need to allocate memory for it (malloc), then we need
to initialize it using igraph_vector_init().

To clear up this vector of vectors, we need to do the reverse:

Destroy each element using igraph_vector_destroy(), then free all of
them using free(), then finally deallocate the memory used by the

Calling igraph_vector_ptr_destroy_all() does exactly this: it calls
element destructors, frees elements, and destroys the vector_ptr.

Calling igraph_vector_ptr_free_all()  calls element destructors and
frees all elements, but does not resize or free the vector_ptr.

Calling igraph_vector_ptr_clear() calls element destructors and
resizes the vector_ptr to length 0. BUT IT DOES NOT FREE ANY ELEMENTS.
This is stated in the documentation.

Given that the vector_ptr is already resized to 0, *conceptually* it
is empty.  How can I then free the elements manually? I do not have
access to them anymore.

Should I free the elements BEFORE using igraph_vector_ptr_clear()?  I
can do that.  But then I need to destroy the elements first with
igraph_vector_destroy(), and only use free() afterwards.  Now when I
call igraph_vector_ptr_clear(), then it will try to free the elements
a second time because there is an item destructor set.

So there seems to be no good way to use igraph_vector_ptr_clear().

 -  If I do free() manually in advance, then I am forced to also
destroy elements manually.  In this case igraph_vector_ptr_clear()
would cause a double destruction.

 - If I do not  do free(), then I lose access to the elements to be
free()d after igraph_vector_ptr_clear() has run.

What is the correct usage of this function then?


reply via email to

[Prev in Thread] Current Thread [Next in Thread]