Runtime Stack allocation

A

Adam

Is there a way in C++ to allocate a variable amount of stack space at
run-time?

void complex_maths_operation(const int num_rows, double* vector)
{
double temp[num_rows];
....
}

The obvious answer is to use the heap... but if this isn't an option.
 
R

Rolf Magnus

Adam said:
Is there a way in C++ to allocate a variable amount of stack space at
run-time?

Well, there is the class std::stack, but I doubt that you are referring to
that. However, other than that, C++ doesn't define anything called "stack".
 
J

Jeff Schwab

Adam said:
Is there a way in C++ to allocate a variable amount of stack space at
run-time?

void complex_maths_operation(const int num_rows, double* vector)
{
double temp[num_rows];
....
}

The obvious answer is to use the heap... but if this isn't an option.

Recurse. Your base case can depend on a run-time variable.
 
A

Andrey Tarasevich

Adam said:
Is there a way in C++ to allocate a variable amount of stack space at
run-time?

void complex_maths_operation(const int num_rows, double* vector)
{
double temp[num_rows];
....
}

The obvious answer is to use the heap... but if this isn't an option.
...

There's no C++-standard way to do that.

If you don't mind going outside the limits of C++ standard, look up the 'alloca'
function. It does exactly what you want but has some limitations, which might be
(or might not be) critical in your case.
 
A

Adam

Thanks Andrey,

Yes, 'alloca' style allocation is what I was looking for.
This sort of behavor is supported by Ada and I've become fond of it.

Adam

Andrey Tarasevich said:
Adam said:
Is there a way in C++ to allocate a variable amount of stack space at
run-time?

void complex_maths_operation(const int num_rows, double* vector)
{
double temp[num_rows];
....
}

The obvious answer is to use the heap... but if this isn't an option.
...

There's no C++-standard way to do that.

If you don't mind going outside the limits of C++ standard, look up the
'alloca' function. It does exactly what you want but has some limitations,
which might be (or might not be) critical in your case.
 
M

Matthias Buelow

Adam said:
Yes, 'alloca' style allocation is what I was looking for.
This sort of behavor is supported by Ada and I've become fond of it.

Don't allocate too much with alloca(), on most systems, there's a lot
less stack space than heap space available with default settings.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,076
Latest member
OrderKetoBeez

Latest Threads

Top