0

How can you dynamically allocate memory using stack ( not heap )?

Do they need different functions than malloc(),calloc() ? Which header file is used?

2 Answers 2

3

alloca(3) is the function you're looking for.

void test_alloca(int num)
{
    int *myarray = alloca(num * sizeof(int));

    // do not try to free(myarray) !
}

In C99 you can also declare a variable-length array:

void test_vla(int num)
{
    int myarray[num];
}

These two code snippets are functionally identical. (An exception being that the first declares a pointer while the second declares an array, leading to different results if you take the sizeof(myarray).)

Sign up to request clarification or add additional context in comments.

1 Comment

Don't we need to do type casting in alloca ? and can't i declare variable length array when allocation is done on heap ? also i want to know why we need to allocate memory on stack for what reasons or can there be any situations where its must ??
1

The sentence in your question

dynamically allocate memory using stack

is a bit broad. However, In my opinion, you have two options,

  1. Use alloca(), prototyped in <alloca.h>
  2. Use VLA C99 and above

But remember the fundamental difference, the lifetime of the allocated memory through aforesaid process will be limited by their scope.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.