Exercise: Fix the Memory Bug

Write code to solve the problem.

Question

The following program attempts to return an array from a function. However, the program behaves incorrectly because the array was created on the stack, and its memory becomes invalid after the function returns.

Your task is to fix the program so that it correctly returns the array. Fix the function so that:

  1. The array is allocated on the heap instead of the stack.

  2. The program correctly prints the values.

  3. The allocated memory is properly freed in main().

Expected output:

0 2 4 6 8

Exercise: Fix the Memory Bug

Write code to solve the problem.

Question

The following program attempts to return an array from a function. However, the program behaves incorrectly because the array was created on the stack, and its memory becomes invalid after the function returns.

Your task is to fix the program so that it correctly returns the array. Fix the function so that:

  1. The array is allocated on the heap instead of the stack.

  2. The program correctly prints the values.

  3. The allocated memory is properly freed in main().

Expected output:

0 2 4 6 8
C
#include <stdio.h>
int* create_array(int n) {
int arr[n];
for (int i = 0; i < n; i++) {
arr[i] = i * 2;
}
return arr; // BUG: returning stack memory
}
int main() {
int n = 5;
int *numbers = create_array(n);
for (int i = 0; i < n; i++) {
printf("%d ", numbers[i]);
}
return 0;
}