473,396 Members | 1,929 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

why new dynamic stack allocation in C++?

Tom
What I mean is why can I only allocate const size stuff on the stack in C++? If I want to allocate a variable amount I need to use the OS API (Win32 in my case).

Thanks,
Tom.
Jul 22 '05 #1
9 4942
"Tom" <bl**@blah.com> wrote...
What I mean is why can I only allocate const size stuff on the stack in

C++? If I want to allocate a variable amount I need to use the OS API
(Win32 in my case).

What are you talking about? Please read the FAQ 5.8. You can
find FAQ here: http://www.parashift.com/c++-faq-lite/

Victor
Jul 22 '05 #2
Tom wrote:
What I mean is why can I only allocate const size stuff on the stack in C++? If I want to allocate a variable amount I need to use the OS API (Win32 in my case).

Thanks,
Tom.

That is the whole point os having a stack and a heap! If you want to
allocated space, of amounts unknown at compile time, but known at
runtime, then you use the heap.

Java is the same.

Not sure about other langs.

~S

Jul 22 '05 #3
"Shea Martin" <sm*****@arcis.com> wrote in message
news:uZLyb.16132$f7.770588@localhost...
Tom wrote:
What I mean is why can I only allocate const size stuff on the stack in C++? If I want to allocate a variable amount I need to use the OS API
(Win32 in my case).
Thanks,
Tom.

That is the whole point os having a stack and a heap! If you want to
allocated space, of amounts unknown at compile time, but known at
runtime, then you use the heap.

Java is the same.

Not sure about other langs.

~S


I don't agree. There is a good reason to do dynamic allocation on the
stack. When I allocate I do:
(1) automatic (stack) allocation, with objects of fixed (compile time)
sizes.
(2) dynamic (heap) allocation, with the new operator.
(3) dynamic heap allocation using _alloca (win32 only). I only do this with
speed sensitive code. So, instead of writing something like this:

void MyFunc( size_t s )
{
char* p = new char[ s ];
....
delete p;
}

I write something like this:

void MyFunc( size_t s )
{
char* p = (char*) _alloca( nBufSize + 1 );
....
}

So, am I missing something? Is this not faster?

Tom.
Jul 22 '05 #4
Bell wrote:
"Shea Martin" <sm*****@arcis.com> wrote in message
news:uZLyb.16132$f7.770588@localhost...
Tom wrote:
What I mean is why can I only allocate const size stuff on the stack in
C++? If I want to allocate a variable amount I need to use the OS API
(Win32 in my case).
Thanks,
Tom.


That is the whole point os having a stack and a heap! If you want to
allocated space, of amounts unknown at compile time, but known at
runtime, then you use the heap.

Java is the same.

Not sure about other langs.

~S

I don't agree. There is a good reason to do dynamic allocation on the
stack. When I allocate I do:
(1) automatic (stack) allocation, with objects of fixed (compile time)
sizes.
(2) dynamic (heap) allocation, with the new operator.
(3) dynamic heap allocation using _alloca (win32 only). I only do this with
speed sensitive code. So, instead of writing something like this:

void MyFunc( size_t s )
{
char* p = new char[ s ];
....
delete p;
}

I write something like this:

void MyFunc( size_t s )
{
char* p = (char*) _alloca( nBufSize + 1 );
....
}

So, am I missing something? Is this not faster?

Tom.

I have never used the _alloca() funtion. My programming experience with
the win32 api has been minimal. But I have a fairly good guess what it
does:

_alloca is allocating a chunk of memory at startup, and then just giving
it out peice by peice, until it runs out, then grabs another large
chunk. Thus, reducing the actual number of mallocs(). Similar to the
difference b/n read() and fread. Again, the gain is speed, the loss
would be possible wasted memory.

*If* my assumption is correct, you can implement similar behavior to the
_alloca function my defining operator new().

~S

Jul 22 '05 #5
Stack allocations cannot be dynamic. They are determined
by the local variable declarations in your code.

The following article should clarify stack operations (see the section
on function calling):

http://www.eventhelix.com/RealtimeMa...ranslation.htm

Sandeep
--
http://www.EventHelix.com/EventStudio
EventStudio 2.0 - Generate Sequence Diagrams and Use Case Diagrams in PDF
Jul 22 '05 #6
Shea Martin <sm*****@arcis.com> wrote:
Tom wrote:
What I mean is why can I only allocate const size stuff on the stack in
C++? If I want to allocate a variable amount I need to use the OS API
(Win32 in my case).
That is the whole point os having a stack and a heap! If you want to
allocated space, of amounts unknown at compile time, but known at
runtime, then you use the heap.


There is no intrinsic reason for this. On just about any architechure,
you can issue an instruction to "bump the stack pointer", provided
more stack-allocated memory. There is no intrinsic reason the
parameter has to be provided at compile time.
Java is the same.
In Java, all arrays go on the heap anyway, so the issue never comes
up.
Not sure about other langs.


C99 has a primitive called a "variable length array". You can do this
in C99,

void f(const char *s)
{
char new_string[strlen(s) + 1];
strcpy(new_string, s);
}

I don't believe C99 mandates that vararrays always produce stack
memory, but the intent is that an implementation will do that for
nonpathological cases. Whether or not some equivalent will get into
C++0x, no one really knows. The main argument against it (that I know
of) is that it would discourage people from using vectors. The
argument for is that everyone does it already, with nonstandard
'alloca' macros, but those macros have annoying differences on some
platforms, especially in the presense of exceptions.

--
Dave O'Hearn
Jul 22 '05 #7
> > I don't agree. There is a good reason to do dynamic allocation on
the
stack. When I allocate I do:
(1) automatic (stack) allocation, with objects of fixed (compile time) sizes.
(2) dynamic (heap) allocation, with the new operator.
(3) dynamic heap allocation using _alloca (win32 only). I only do this with speed sensitive code. So, instead of writing something like this:

void MyFunc( size_t s )
{
char* p = new char[ s ];
....
delete p;
}

I write something like this:

void MyFunc( size_t s )
{
char* p = (char*) _alloca( nBufSize + 1 );
....
}

So, am I missing something? Is this not faster?

Tom.

I have never used the _alloca() funtion. My programming experience

with the win32 api has been minimal.
Equivalents of alloca() can be found on other platforms too.
But I have a fairly good guess what it
does:

_alloca is allocating a chunk of memory at startup, and then just giving it out peice by peice, until it runs out, then grabs another large
chunk.


That is not the way alloca() works. The reason it is fast is that it
just decrements the stack pointer by a specified amount of bytes. The
memory "allocated" by alloca() is on the stack. As a result this
function may result in a stack overflow when trying allocate too much
memory.

Though it may be very fast, I would use this function only as a last
resort.

--
Peter van Merkerk
peter.van.merkerk(at)dse.nl


Jul 22 '05 #8
"Bell" <bl**@neesus.com> wrote in message news:<aR******************@news20.bellglobal.com>. ..
"Shea Martin" <sm*****@arcis.com> wrote in message
news:uZLyb.16132$f7.770588@localhost...
Tom wrote:
What I mean is why can I only allocate const size stuff on the stack in C++? If I want to allocate a variable amount I need to use the OS API
(Win32 in my case).
Thanks,
Tom.

That is the whole point os having a stack and a heap! If you want to
allocated space, of amounts unknown at compile time, but known at
runtime, then you use the heap.

Java is the same.

Not sure about other langs.

~S


I don't agree. There is a good reason to do dynamic allocation on the
stack. When I allocate I do:
(1) automatic (stack) allocation, with objects of fixed (compile time)
sizes.
(2) dynamic (heap) allocation, with the new operator.
(3) dynamic heap allocation using _alloca (win32 only). I only do this with
speed sensitive code. So, instead of writing something like this:

void MyFunc( size_t s )
{
char* p = new char[ s ];
....
delete p;
}

I write something like this:

void MyFunc( size_t s )
{
char* p = (char*) _alloca( nBufSize + 1 );
....
}

So, am I missing something? Is this not faster?

Tom.


It is faster and it also exists on linux (actually it's a matter of
compiler. alloca is implemented by decreasing the stack pointer.
alloca() is a builtin of the compiler (for gcc at least)).
So alloca is pretty safe. The problem is: what about objects
with virtual tables?

A dirty hack is:

class A { ... }; /* virtuals in there! */
A vtblpy;

int f ()
{
A *p = alloca (sizeof (A));
*p = vtblcpy;
// or
memcpy (p, &vtblcpy, sizeof *p);

p->initialization (...); // instead of ctor
}

This worked once, but you'll get an 'F' in programming from the
professors:)

Anyway, I think C# has something like that called stackalloc.
So it is useful.

stelios
Jul 22 '05 #9
Tom wrote:
What I mean is,
"Why can I only allocate const size stuff on the stack in C++?"
If I want to allocate a variable amount,
I need to use the OS API (Win32 in my case).
The Gnu C++ compiler will allocate variable-arrays on the stack
cat main.cc #include<iostream>

int main(int argc, char* argv[]) {
int n = atoi(argv[1]);
double a[n];
for (int j = 0; j < n; ++j)
a[j] = j;
return 0;
}
g++ -Wall -o main main.cc
g++ -Wall -ansi -pedantic -o main main.cc

main.cc: In function `int main(int, char**)':
main.cc:5: warning: ISO C++ forbids variable-size array `a'

Variable-arrays are supported by the ANSI/ISO C99 standard and
we expect that future ANSI/ISO C++ standards will adopt them as well.
Just be patient.

Jul 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: chris | last post by:
Hi all, I need to know, what is the difference between dynamic memory allocation, and stack allocation ? 1. If I have a class named DestinationAddress, when should I use dynamic memory...
13
by: xian_hong2046 | last post by:
Hello, I think dynamic memory allocation is supposed to be used when one doesn't know in advance how much memory to allocate until run time. An example from Thinking in C++ is to dynamically...
11
by: toton | last post by:
Hi, I have little confusion about static memory allocation & dynamic allocation for a cluss member. I have class like class Bar{ public: explicit Bar(){ cout<<"bar default"<<endl; }
7
by: Jo | last post by:
Hi, How can i differentiate between static and dynamic allocated objects? For example: void SomeFunction1() { CObject *objectp = new CObject; CObject object;
31
by: Markus Pitha | last post by:
Hello, I'm using a template to simulate a LinkedList from Java.It works without problems, but when I want to use strings in main.cpp instead of char*, I get the following error message: $...
14
by: vivek | last post by:
i have some doubts on dynamic memory allocation and stacks and heaps where is the dynamic memory allocation used? in function calls there are some counters like "i" in the below function. Is...
13
by: kwikius | last post by:
Does anyone know what a C99 dynamic array is, and if it will be useable in C++? regards Andy Little
10
by: swornavidhya.mahadevan | last post by:
Which allocation (Static / Dynamic) is suitable for the situation when we are trying to allocate for a overloaded memory when the memory is full and no space to allocate. What will happen if both...
5
by: mike.m.schmidt | last post by:
Hello, I've been trying to optimize a piece of code that executes in 6 milliseconds. From what I have read, dynamically managing memory with new/malloc and delete/free is less efficient than...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.