-1

Hello I am learning basic of c programming and having a little difficulty understanding the behavior of these codes.

this is the first one:

#include <stdio.h>
#include <stdlib.h>

int* foo(int start) {
  int arr[3];
  arr[0] = start;
  arr[1] = start+1;
  arr[2] = start+2;

  int* ret = arr;
  return ret;
}

int main() {
  int* a1 = foo(0);
  int* a2 = foo(3);
  printf("a1 = [%d, %d, %d]\n", a1[0], a1[1], a1[2]);
  printf("a2 = [%d, %d, %d]\n", a2[0], a2[1], a2[2]);
  return 0;
}

I expected this to print

a1 = [0,1,2]

a2 = [3,4,5], but it prints

a1 = [3, 4, 5]
a2 = [32766, -463722864, 32766]

like this. But When I change the code to ;

int* foo(int start) {
  int* arr = (int*) malloc(3*sizeof(int));
  arr[0] = start;
  arr[1] = start+1;
  arr[2] = start+2;
  int* ret = arr;
  return ret;
}

it works as I expect. why is the first one not working? I want to understand why this is the case. thank you

1 Answers1

1

In the first code, you return a reference to the local variable arr which stops existing when the function returns.

in the second code, you return the reference to the dynamically allocated memory which exists until you free it intentionally or program terminates.

0___________
  • 60,014
  • 4
  • 34
  • 74