Hello ,
i have read the manual page of alloca ,

it is documented there that "alloca works similar to the malloc but it allocates memory from stack and frees automatically.

i can't get how can i use that in a program .

if i'm not wrong can i use that like :

#include<stdio.h>
#include<alloca.h>
int main()
{
        void *p;
        p=alloca(200);
        if(p==NULL)
        {
                printf("alloca failed\n");
                exit(1);
        }
        strcpy(p,"Hello");
        printf("%s\n",p);
        printf("%u\n",p);
        return 0;
}

and what is the advantage of such a function.

even if i use array it also allocates memory from the stack and memory will be freed automatically.
what is the more advantage its having than array

alloca is similar to malloc in that you can allocate memory dynamically, however the memory is automatically freed when you exit the function that called alloca.

With an array you can't compute the storage required at runtime.

i can't get how can i use that in a program .

alloca() is used just like malloc(). The difference is how they work under the hood.

and what is the advantage of such a function.

  • alloca() is faster because it just needs to adjust the stack pointer. malloc() has a lot of bookkeeping on top of requesting heap memory.
  • alloca() is easier to use because you do not need a corresponding call to free() like with malloc().

Unfortunately, the disadvantages outweigh the advantages such that alloca() is not recommended. Here is what NetBSD's man page says:

BUGS
The alloca() function is machine dependent; its use is discouraged.

The alloca() function is slightly unsafe because it cannot ensure that
the pointer returned points to a valid and usable block of memory. The
allocation made may exceed the bounds of the stack, or even go further
into other objects in memory, and alloca() cannot determine such an
error. Avoid alloca() with large unbounded allocations.

alloca() stores the data in stack memory ,whereas malloc() stores data in heap memory

by the way ,we know that stack is faster than heap...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.