0
#include<cstdio>

int *f1(){

    int arr[10] = {1,2,3,4,5,6,7,8,9,10};

    return arr;
}


int main(){

    printf("%d", *(f1()+3));
    // printf("%d", f1()[3]);

    return 0;

}   

The code above gives Segmentation fault at runtime. But I don't understand why. I am creating an integer array in my f1() function and filling it with values. Then returning the address of that array(address of the first element). So, I expect to be able to reach it from main. However, apparently, I cannot do it.

Barmar
  • 741,623
  • 53
  • 500
  • 612
mya
  • 11
  • 4
  • As `arr` is a local variable it’s on the stack - once the function returns that is no longer available and attempting to access it is doomed. Use `malloc` Maybe? – DisappointedByUnaccountableMod Apr 10 '20 at 16:20
  • @barny yes, using `malloc` gave the desired result. So, I don't have much information about stack and heap, but from this example, is using `malloc` allocates memory in heap instead of stack and so it is why it works with malloc? – mya Apr 10 '20 at 16:56
  • Yes - the catch is that you have to remember to `free` the allocation when you no longer need it, otherwise memory usage will keep increasing, an effect usually referred as a memory leak. A better design would almost always be to pass a pointer into the function rather than it calling malloc and expecting the free to be done elsewhere. – DisappointedByUnaccountableMod Apr 10 '20 at 18:28
  • @barny yes, I also tried by passing the array and it seems a better idea too. The memory gets cleaned automatically after the program executes and finishes right? – mya Apr 10 '20 at 19:08
  • Yes all memory is released when your program exits - but don’t use that as a reason not to correctly free every malloc! – DisappointedByUnaccountableMod Apr 10 '20 at 21:18
  • @barny OK, thanks for the all. – mya Apr 10 '20 at 22:22

0 Answers0