Alloca example of memory allocation in stack

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.