One could lead to undefined behaviour and second definitely could lead to undefined behaviour.
It is all about wide known and liked freeing memory without setting variable to null.
So to prevent I have provided two macros to destroy vectors.
#define VECTOR$DESTROY(obj) {vector$destroy(obj); obj = NULL;}and
#define VECTOR$DESTROYWN(obj) {vector$destroyWithNodes(obj); obj = NULL;}This allow to freeing memory and do not let you forget to set pointer to NULL. I think it is obvious that it is better to crash program then to let it do weird and unexpected things.
The second snag arises when user destroy vector node data but forget to set node itself to null. Then, when iterating over vector it still points to the memory we had freed. But as long as vector does not know anything about data it stores (it has only pointer to it), it is not able to properly destroy node.
The solution is that vector now provides a delegate called destroyNode. As default it is connected with lambda function (which is declared in auxilary module). Lambda does not do anything but returns first passed argument.
If you want to vector takes care about destroying nodes you are responsible for register proper function which can do it.
Best would be to provide example:
Providing that we store Strings in our vector:
function which can properly destroy node:
Vector* destroyStringNode( Vector* v, ulong idx ) {
Strings *s = (Strings*) v->get(v,idx);
STRINGS$DESTROY(s); v->deleteNode(v,idx);
return v;
}
in some function register it to the vector:
...
...
Vector *myV = vector$new(0);
myV->regDestroyNode( myV, &destroyStringNode );
...
Now, we can safely destroy node 2 by:
myV->destroyNode( myV, 2 );
or at the end use:
VECTOR$DESTROYWN( myV );
which let us make sure that there is no memory leakage.
Of course, if we want to destroy only vector but no data (and we have pointers to them), we still can:
myV->deleteNode(myV, 2);
and
VECTOR$DESTROY( myV );
I decided that better would be to place code to pasteAll.org, and there are links:
auxilary.h
auxilary.c
vector.h
vector.c
main.c
No comments:
Post a Comment