OK, I have this piece of code:
typedef struct faux_crit
{
char dna[DNALEN+1]; //#define'd to 16
int x, y;
int age;
int p;
int dir;
} crit;
crit *makeguy(int x, int y)
{
crit *guy;
guy = (crit *) malloc(sizeof(crit));
strcpy(guy->dna, makedna());
guy->x = x;
guy->y = y;
guy->age = guy->p = guy->dir = 0;
return guy;
}
char *makedna()
{
char *dna;
int i;
dna = (char *) malloc(sizeof(char) * DNALEN+1);
for(i = 0; i < DNALEN; i++)
dna[i] = randchar();
return dna;
}
int main()
{
int i;
crit *newguy;
srand((unsigned) time(0));
newguy = makeguy(0, 0);
/*[..]
just printing things here
*/
free(newguy);
return 0;
}
I'd just want to know what did I wrong with managing memory, because valgrind reports a memory error. I presume it's the dna var in makedna, but when should I free it? I don't have access to it after leaving the function, and I need to return it, so I can't free it before that.
EDIT: Okay, thank you all.