C: Fix the vanishing array

This function returns memory that no longer exists. Fix it.

What to build

A function that returns an array safely.

Requirements

  • Change make_squares so that the memory it returns stays valid after it returns.
  • Free that memory in main once it has been used.
  • Print the squares of 1 to n, separated by single spaces.

Input

One whole number n.

Output

One line.

Constraints

n is from 1 to 100.

Example

Input:

3

Output:

1 4 9

Why it works

A local array disappears with its frame. The heap keeps memory until it is freed, so it can be handed back to the caller, who then has to free it.

Examples

Example 1 · Input
3
Expected output
1 4 9
Example 2 · Input
1
Expected output
1

Hints

Hint 1

Where does the array in make_squares live, and when does it stop existing?

Hint 2

Use malloc to make memory that outlives the function.

Hint 3

main becomes responsible for freeing it.

Solution

Show one correct solution (try it yourself first)
#include <stdio.h>
#include <stdlib.h>

int *make_squares(int n) {
    int *squares = malloc(n * sizeof(int));
    if (squares == NULL) {
        return NULL;
    }
    for (int i = 0; i < n; i++) {
        squares[i] = (i + 1) * (i + 1);
    }
    return squares;
}

int main(void) {
    int n;
    scanf("%d", &n);
    int *s = make_squares(n);
    if (s == NULL) {
        return 1;
    }
    for (int i = 0; i < n; i++) {
        printf(i ? " %d" : "%d", s[i]);
    }
    printf("\n");
    free(s);
    return 0;
}

Lesson: Bugs C will not catch →