I have some questions about program stack.
I'm trying to give input array, process them and return processed array.(want to save the input array.) And trying to avoid using globals.
English is not mother tongue so please forgive my English..!
int* func(int* input_array, int size)
{
int arr_local[20] = { };
int* arr_alloc = (int*)malloc(sizeof(int)* 3);
for (int i = 0; i < size; i++)
{
arr_local[i] = input_array[i];
}
arr_local[3] = 4;
/*for (int i = 0; i < size; i++)
{
arr_alloc[i] = input_array[i];
}
arr_alloc[3] = 4;
free(arr_alloc);*/
// return arr_alloc;
return arr_local;
}
int main()
{
int input_arr[20] = { 0, };
printf("%d", func(input_arr,10)[3]);
}
1-1. When I return local_arr which is declared as a local variable in my_func, it works normally in debug mode. but I assume that it's not a good way.
1-2. Program stack is determined on compile time, isn't it?
1-3. Is the program stack is immutable during runtime?
1-4. I guessed if program stack is immutable, I could return arr_local.
2-1 When I used malloc to use heap segment. Can I free(arr_alloc) outside the scope from where it allocated? if it's possible. Is it recommend or not?
2-2 I did free(arr_alloc) before return arr_alloc but it works fine. Is it only because arr_alloc heap memory hasn't been overwrited yet?
3-1 What would be a good code to handle array.