Open In App

alloca() function its advantages and disadvantages

Last Updated : 25 Aug, 2022
Like Article

What is alloca() function?

The function alloca() is used to allocate memory for a stack frame. It’s just an unconventional method of dynamically allocating memory. When a function returns its value or the defined memory’s scope expires, the memory is automatically released.

A void pointer pointing to the beginning of the allocated memory is the result of this function. Even if we just allocate memory with a size of 0, it will still do so and return the void pointer for that starting location.

Advantages of alloca() function:

  • It provides faster allocation of the memory.
  • It uses very little extra space to allocate memory.
  • It does not cause memory fragmentation and space allocated to one block can be reused by another block of another size as it doesn’t contain any separate memory for different size blocks.
  • It automatically frees up the space when the function returns its value unlike malloc(), in which we have to remove the space allocated by the function.

Disadvantages of alloca() function:

  • Memory allocated by alloca() function is fixed and cannot be changed, and if you try to exceed that limit then you will get a segmentation fault for accessing memory that was not allocated.
  • Some system does not support alloca() function due to which it is not advisable to use this function instead of this, it is preferable to use the malloc() function in C programs.
  • It is dependent on the compiler as well as the machine.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads