0

This is a code that I have written based on 2013 Section question. I put free at the getAge() function but it is still returning error after running valgrind through it. I really dont know why. Any help is appreciated. Thank you.

#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
int* getAge(void);
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        printf("Usage: copy infile outfile\n");
        return 1;
    }

    if (argv[1] <= 0)
    {
        printf("Usage: copy infile outfile\n");
        return 2;
    }
    int a = atoi(argv[1]);
    int* size[a];
    // get ages
    for (int i = 0; i < a; i++)
    {
        size[i] = getAge();
    }
    int oldest = 0;
    for (int i = 0; i < a; i++ )
    {
        if  (*size[i] > oldest)
           {
               oldest = *size[i];
            }
    }
    printf("the oldest is %i years old\n", oldest);
}

int* getAge(void)
{
    // get an age
    int* age = (int*)malloc(sizeof(int));
    do
    {
        *age = get_int("how old is the d\n");
    }
    while (*age < 1);
    //return the age
    return age;
    free(age);
}

2
  • Order matters. The last thing that getAge will execute is the return age. To be clear valgrind will report memory issues, it will not fix them. Dec 23, 2019 at 11:36
  • In this code example, I can't solve the problem by swapping return() and free() because it would free the memory before returning it. Any idea how to solve it? Dec 23, 2019 at 12:58

1 Answer 1

0

[Answer based on the "trainer" exercise found here].

The free(age); never runs, because it is after the return. But where is the program storing that pointer? After all the inputs are done, size is an array of the pointers created in getAge.

When program is done "using" them, then it would be appropriate (and necessary) to free them.

You must log in to answer this question.

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