The following function "increment" add 1 to a number represented as an array.
int* increment(int array[], int size, int *sizeLen)
{
int temp[size+1];
int carry = 0;
carry = (array[size-1]+1)/10;
temp[size] = (array[size-1]+1)%10;
for(int i=size-2;i>=0;i--)
{
temp[i+1] = (array[i] + carry)%10;
carry = (array[i]+carry)/10;
}
if(carry)
{
temp[0] = 1;
*sizeLen = size+1;
return temp;
}
else
{
*sizeLen = size;
return (temp+1);
}
}
int main()
{
int array[] = {9,9,9};
int length;
int *res = increment(array, sizeof(array)/sizeof(int), &length);
for(int i=0;i<length;i++)
{
cout << res[i] << " ";
}
}
I know gcc supports variable length arrays and they are stored on stack. I expect temp to go out of scope once this function ends and the attempt to print the array in main should print garbage values. But in my case the actual values are printed. When does the variable length array declared in the function goes out of scope?
The key here is indeed the storage duration of the array. It has automatic storage duration. The lifetime of variables with automatic storage duration ends the moment the scope they're are in is exited.
It does exactly as you expect. But nothing in C stops you from taking the address of a local object and returning it from the function.
Using that pointer is undefined behavior. It may appear to work, but the array is still for all intents and purposes "dead". Such pointers are known colloquially as "dangling pointers".
Well, the above is true for C. Since this is about the GCC extension, the same applies mostly, but may need to be taken with a grain of salt.