Declaring a local variable must be allocated on the stack, but is there any way?
Of course, it's alloca.
The following code shows how to use alloca in the variable-length conversion parameter.
int main(int argc, char ** argv) { char **argv2; int i,n; n=0; while(argv[n] != NULL) n++; printf("n %d\n",n); argv2 = alloca((n + 2) * sizeof(*argv)); argv2[0] = "program"; for( i=0; i <= n; i++) argv2[i+1] = argv[i]; argv2[n+2] = NULL; i = 0; while( argv2[i] != NULL) printf("%s\n",argv2[i++]);}
(Of course: this example is not comprehensive. We should write alloca into a function, but the memory is released when this function returns)
Ref: http://baike.baidu.com/view/3977355.htm? Fr = Aladdin
When the alloca () function is called to return, the memory allocated by it is automatically released. That is to say, the allocation with alloca exists to some extent in the ''stack frames "or context of the function. Alloca () is not portable and is hard to implement on machines without traditional stacks. When its return value is directly passed into another function, it may cause problems, such as fgets (alloca (100), 100, stdin ). For these reasons, alloca () is not a standard and should not be used in a program that must be widely transplanted, no matter how useful it may be. Since c99 supports variable-length array (VLA), it can be used to better complete previous tasks of alloca.
Alloca example of memory allocation in stack