hi,
#include <stdio.h>
int* get_int()
{
int arr[100];
arr[0] = 5;
printf("arr %p\n",arr);
return arr;
}
int main()
{
int* p = get_int();
printf("got %p\n",p);
return 0;
}
for the code above I get this warning message:
test-heap.c: In function ‘int* get_int()’:
test-heap.c:5: warning: address of local variable ‘arr’ returned
My question is whether this above approach is right or wrong. ie getting the storage allocation for the pointer in main function done indirectly through the function get_int. If I call get_int repeatedly in a loop then is it necessary to free p before the beginning of each iteration as for different iteration it is supposed to get different allocation but I am not sure what happens to the previous allocation. Is there any possibility of memory leak? Suppose I allocated a pointer in get_int instead of creating an array then would that be treated differently from within main I mean allocation/deallocation(calling malloc/free) wise?
Thanks.