0

When I run Check50 I get an error. I have watched the hint video and my code matches what is shown. I have attached a screenshot of my error as well as the code below. Thank you for the help!

person *create_family(int generations)
{
    // TODO: Allocate memory for new person
    person *p = malloc(sizeof(person));

    // Generation with parent data
    if (generations > 1)
    {
        // TODO: Recursively create blood type histories for parents
        p->parents[0] = create_family(generations - 1);
        p->parents[1] = create_family(generations - 1);

        // TODO: Randomly assign child alleles based on parents
        p->alleles[0] = p->parents[0]->alleles[rand() % 2];
        p->alleles[1] = p->parents[1]->alleles[rand() & 2];
    }

    // Generation without parent data
    else
    {
        // TODO: Set parent pointers to NULL
        p->parents[0] = NULL;
        p->parents[1] = NULL;

        // TODO: Randomly assign alleles
        p->alleles[0] = random_allele();
        p->alleles[1] = random_allele();
    }

    // TODO: Return newly created person
    return p;
}

// Free `p` and all ancestors of `p`.
void free_family(person *p)
{
    // TODO: Handle base case
    if (p == NULL)
    {
        return;
    }

    // TODO: Free parents
    free_family(p->parents[0]);
    free_family(p->parents[1]);

    // TODO: Free child
    free(p);
}

enter image description here

1

The valgrind tool is helpful in this case. Adding the necessary functions to a file with your implementation, it points to line 104:

==72356== Conditional jump or move depends on uninitialised value(s)
==72356==    at 0x4A3EF5D: _IO_file_overflow@@GLIBC_2.2.5 (fileops.c:783)
==72356==    by 0x4A27A6D: __vfprintf_internal (vfprintf-internal.c:1688)
==72356==    by 0x4A0FEBE: printf (printf.c:33)
==72356==    by 0x401329: print_family (inheritance.c:104)
==72356==    by 0x4011B0: main (inheritance.c:33)

which is in the template, rather than your code.
printf("Generation %i, blood type %c%c\n", generation, p->alleles[0], p->alleles[1]);

By dividing each of the 3 variables being printed into a separate print statement, it's determined that p->alleles[1] is not set.
Inspection of the code, comparing how [0] is set compared to [1] shows a difference.

    p->alleles[0] = p->parents[0]->alleles[rand() % 2];
    p->alleles[1] = p->parents[1]->alleles[rand() & 2];


By using rand() & 2, the random number is bitwise and-ed with the binary equivalent of 2: 'b10; This causes the index to alleles[] to be either 0 or 2. 2 is out of range, causes an undefined value to be loaded into p->alleles[1].

1
  • Thank you so much! I had racked my brain so much looking for the error that I didn't catch my '&' typo. Also really appreciate you including your thoughts with valgrind.
    – sevo
    Apr 19 at 18:19

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .