#include <stdlib.h>
#include <stdio.h>
typedef struct _Foo_
{
// variables
int number;
char character;
// array of float
int arrSize;
float* arr;
// pointer to another instance
void* myTwin;
} Foo;
Foo* createFoo (int arrSize, Foo* twin);
Foo* destroyFoo (Foo* foo);
int main ()
{
Foo* a = createFoo (2, NULL);
Foo* b = createFoo (4, a);
destroyFoo(a);
destroyFoo(b);
return 0;
}
Foo* createFoo (int arrSize, Foo* twin)
{
Foo
* t
= (Foo
*) malloc(sizeof(Foo
));
// initialize with default values
t->number = 1;
t->character = '1';
// initialize the array
t->arrSize = (arrSize>0?arrSize:10);
t
->arr
= (float*) malloc(sizeof(float) * t
->arrSize
);
// a Foo is a twin with only one other Foo
t->myTwin = twin;
if(twin) twin->myTwin = t;
return t;
}
Foo* destroyFoo (Foo* foo)
{
if (foo)
{
// we allocated the array, so we have to free it
// to avoid broken pointer, we need to nullify the twin pointer
if(foo->myTwin) ((Foo*)foo->myTwin)->myTwin = NULL;
}
return NULL;
}
I2luY2x1ZGUgPHN0ZGxpYi5oPgojaW5jbHVkZSA8c3RkaW8uaD4KCnR5cGVkZWYgc3RydWN0IF9Gb29fCnsKICAgIC8vIHZhcmlhYmxlcwogICAgaW50IG51bWJlcjsKICAgIGNoYXIgY2hhcmFjdGVyOwogICAgCiAgICAvLyBhcnJheSBvZiBmbG9hdAogICAgaW50IGFyclNpemU7CiAgICBmbG9hdCogYXJyOwogICAgCiAgICAvLyBwb2ludGVyIHRvIGFub3RoZXIgaW5zdGFuY2UKICAgIHZvaWQqIG15VHdpbjsKfSBGb287CgpGb28qIGNyZWF0ZUZvbyAoaW50IGFyclNpemUsIEZvbyogdHdpbik7CkZvbyogZGVzdHJveUZvbyAoRm9vKiBmb28pOwoKaW50IG1haW4gKCkKewogICAgRm9vKiBhID0gY3JlYXRlRm9vICgyLCBOVUxMKTsKICAgIEZvbyogYiA9IGNyZWF0ZUZvbyAoNCwgYSk7CiAgICAKICAgIGRlc3Ryb3lGb28oYSk7CiAgICBkZXN0cm95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