473,320 Members | 1,746 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,320 software developers and data experts.

Runtime stack allocation

Hi all,

I'm using a temporary buffer to transfer some data and would rather
not allocate it on the heap. The problem is that the size of the
buffer is only known upon entry into the function that utilizes it and
I'd rather not waste space or dynamically allocate on the heap (since
it doesn't need to persist). Now I'm planning on utilizing inline
assembly to modify the stack pointer directly to allocate the space I
need.

Here's an example:

void doSomeStuff(unsigned size) {
char* rawData;
//INLINED (Intel p4 assembly)
//sub esp, dword ptr [size]
//mov dword ptr [rawData], esp

//do some stuff with the temporary buffer, using rawData to access
it

//INLINED (Intel p4 assembly)
//add esp, dword ptr [size]

}

This should just work, right? Or are there any odd quirks that I should be
aware of that I may not have thought of?

Jun 30 '08 #1
10 2275
kid joe wrote:
Hi all,

I'm using a temporary buffer to transfer some data and would rather
not allocate it on the heap. The problem is that the size of the
buffer is only known upon entry into the function that utilizes it and
I'd rather not waste space or dynamically allocate on the heap (since
it doesn't need to persist). Now I'm planning on utilizing inline
assembly to modify the stack pointer directly to allocate the space I
need.
IMHO using either a VLA or alloca() is infinitely preferable to messing
with the stack pointer directly. Of the two I'd chose VLAs when it is
available. At least it is standard. If not I'd take alloca() or even
use the heap before going for the sort of trickery you illustrate.

Jun 30 '08 #2
kid joe wrote:
Hi all,

I'm using a temporary buffer to transfer some data and would
rather not allocate it on the heap. The problem is that the
size of the buffer is only known upon entry into the function
that utilizes it and I'd rather not waste space or dynamically
allocate on the heap (since it doesn't need to persist). Now
I'm planning on utilizing inline assembly to modify the stack
pointer directly to allocate the space I need.
No need for inline assembler, if there's some portable function,
that will do the trick. However I can only advise, not to use
it. Most implementations of malloc are efficient enough to
compete in performance with...

alloca

Wolfgang Draxinger
--
E-Mail address works, Jabber: he******@jabber.org, ICQ: 134682867

Jun 30 '08 #3
kid joe <sp******@spamtrap.invalidwrites:
I'm using a temporary buffer to transfer some data and would rather
not allocate it on the heap. The problem is that the size of the
buffer is only known upon entry into the function that utilizes it and
I'd rather not waste space or dynamically allocate on the heap (since
it doesn't need to persist). Now I'm planning on utilizing inline
assembly to modify the stack pointer directly to allocate the space I
need.
[...]

My advice: allocate it using malloc() (on the "heap") anyway, and call
free() when you're done with it.

There is no portable and reliable way to do temporary allocations on
the "stack". (The C standard doesn't even guarantee that there is a
"stack" in the sense you probably mean.)

By using assembly language, you limit yourself to a single platform.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jun 30 '08 #4
kid joe wrote:
I'm using a temporary buffer to transfer some data and would rather
not allocate it on the heap. The problem is that the size of the
buffer is only known upon entry into the function that utilizes it and
I'd rather not waste space or dynamically allocate on the heap (since
it doesn't need to persist). Now I'm planning on utilizing inline
assembly to modify the stack pointer directly to allocate the space I
need.

Here's an example:

void doSomeStuff(unsigned size) {
char* rawData;
//INLINED (Intel p4 assembly)
//sub esp, dword ptr [size]
//mov dword ptr [rawData], esp

//do some stuff with the temporary buffer, using rawData to access
it

//INLINED (Intel p4 assembly)
//add esp, dword ptr [size]

}

This should just work, right? Or are there any odd quirks that I should be
aware of that I may not have thought of?
Well, assuming you want to limit your code to only working on a
particular platform or processor, and you know your code won't conflict
with the compiler's optimizations...

malloc()/free() should be fast enough, even if it doesn't "feel" like
the right tool for the job. If not, can you use a VLA? If not, does
your system offer alloca()? Any of those are better than subverting the
compiler (and portability) and confusing people who will read your code
later by using inline assembly.

S
Jun 30 '08 #5
Stephen Sprunk <st*****@sprunk.orgwrites:
[...]
malloc()/free() should be fast enough, even if it doesn't "feel" like
the right tool for the job. If not, can you use a VLA? If not, does
your system offer alloca()? Any of those are better than subverting
the compiler (and portability) and confusing people who will read your
code later by using inline assembly.
Yes, but alloca() isn't much better. Quoting the alloca man page on
one system:

The alloca function is machine and compiler dependent. On many
systems its implementation is buggy. Its use is discouraged.

On many systems alloca cannot be used inside the list of
arguments of a function call, because the stack space reserved
by alloca would appear on the stack in the middle of the space
for the function arguments.

And VLAs have the drawback that there's no way to check whether the
allocation succeeded.

Use malloc(), and remember to free() the space when you're done with
it.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Jun 30 '08 #6
On Mon, 30 Jun 2008 11:47:45 -0500, Stephen Sprunk wrote:
kid joe wrote:
>I'm using a temporary buffer to transfer some data and would rather
not allocate it on the heap. The problem is that the size of the
buffer is only known upon entry into the function that utilizes it and
I'd rather not waste space or dynamically allocate on the heap (since
it doesn't need to persist). Now I'm planning on utilizing inline
assembly to modify the stack pointer directly to allocate the space I
need.

Here's an example:

void doSomeStuff(unsigned size) {
char* rawData;
//INLINED (Intel p4 assembly)
//sub esp, dword ptr [size]
//mov dword ptr [rawData], esp

//do some stuff with the temporary buffer, using rawData to access
it

//INLINED (Intel p4 assembly)
//add esp, dword ptr [size]

}

This should just work, right? Or are there any odd quirks that I should be
aware of that I may not have thought of?

Well, assuming you want to limit your code to only working on a
particular platform or processor, and you know your code won't conflict
with the compiler's optimizations...

malloc()/free() should be fast enough, even if it doesn't "feel" like
the right tool for the job. If not, can you use a VLA? If not, does
your system offer alloca()? Any of those are better than subverting the
compiler (and portability) and confusing people who will read your code
later by using inline assembly.
Thanks for the replies! After doing some research, I can confirm that this
is a solution that most C compilers support (pretty much 99% of all
compilers in current use today).

void *alloca(size_t size) - allocates a block of <sizebytes on the
stack from and returns a pointer to the start of the block, the block
is automatically freed upon return from the function it was called in
(in most implementations)

Here's a slightly informative documentation of one compiler's
implementation:
http://www.datafocus.com/docs/man3/alloca.3.asp

Note that anyone using this should investigate how their compiler
implements alloca(), as it can get sticky when using it within loops
and if statements (due to scoping). Some compilers will release the
memory upon leaving scope (loop-safe), while others will release the
memory upon leaving the function it is called in (can cause stack
bloating when used within loops).

Hope this is helpful for all those who may want to do the same thing.
This function was what I was exactly looking for - rather than
complaining about this being off topic, infer based upon what I was
trying to do that I was looking for C solution to stack allocation and
was going towards the inline assembly route.

From the poor ability of inference in here, it seems the majority of
you would be better suited for the legal profession rather than
engineering profession - I've seen similar attitudes in many posts
here, whats the deal with trying to be as useless as possible?

Jun 30 '08 #7
kid joe wrote:
On Mon, 30 Jun 2008 11:47:45 -0500, Stephen Sprunk wrote:
>kid joe wrote:
>>I'm using a temporary buffer to transfer some data and would rather
not allocate it on the heap. The problem is that the size of the
buffer is only known upon entry into the function that utilizes it
and I'd rather not waste space or dynamically allocate on the heap
(since it doesn't need to persist). Now I'm planning on utilizing
inline assembly to modify the stack pointer directly to allocate the
space I need.
[...]
>>This should just work, right? Or are there any odd quirks that I
should be aware of that I may not have thought of?

Well, assuming you want to limit your code to only working on a
particular platform or processor, and you know your code won't
conflict with the compiler's optimizations...

malloc()/free() should be fast enough, even if it doesn't "feel" like
the right tool for the job. If not, can you use a VLA? If not, does
your system offer alloca()? Any of those are better than subverting
the compiler (and portability) and confusing people who will read
your code later by using inline assembly.

Thanks for the replies! After doing some research, I can confirm that
this is a solution that most C compilers support (pretty much 99% of
all compilers in current use today).

void *alloca(size_t size) - allocates a block of <sizebytes on the
stack from and returns a pointer to the start of the block, the block
is automatically freed upon return from the function it was called in
(in most implementations)

Here's a slightly informative documentation of one compiler's
implementation:
http://www.datafocus.com/docs/man3/alloca.3.asp

Note that anyone using this should investigate how their compiler
implements alloca(), as it can get sticky when using it within loops
and if statements (due to scoping). Some compilers will release the
memory upon leaving scope (loop-safe), while others will release the
memory upon leaving the function it is called in (can cause stack
bloating when used within loops).

Hope this is helpful for all those who may want to do the same thing.
This function was what I was exactly looking for - rather than
complaining about this being off topic, infer based upon what I was
trying to do that I was looking for C solution to stack allocation and
was going towards the inline assembly route.
Curious, but why do you insist so on "stack allocation"? Is it to avoid
remembering to free later? Is this function speed critical?
From the poor ability of inference in here, it seems the majority of
you would be better suited for the legal profession rather than
engineering profession - I've seen similar attitudes in many posts
here, whats the deal with trying to be as useless as possible?
Not at all. Notice that several respondents did point out to you the
option of alloca and of VLAs. In engineering or science it pays to be
as thourough as possible.

Jul 1 '08 #8
In article <pa****************************@spamtrap.invalid >,
kid joe <sp******@spamtrap.invalidwrote:
....
>Hope this is helpful for all those who may want to do the same thing.
This function was what I was exactly looking for - rather than
complaining about this being off topic, infer based upon what I was
trying to do that I was looking for C solution to stack allocation and
was going towards the inline assembly route.

From the poor ability of inference in here, it seems the majority of
you would be better suited for the legal profession rather than
engineering profession - I've seen similar attitudes in many posts
here, whats the deal with trying to be as useless as possible?
Welcome to clc! Hope you enjoy your stay.

My own view is that the clc culture is much more like the Church and
organized religion (which is to say, total scum) rather than the legal
profession. It is an insult to the legal profession to compare it to clc.

And yes, like the Church, they have perfected the art of being useless
to a high art form.

Jul 2 '08 #9
On 30 Jun, 22:37, kid joe <spamt...@spamtrap.invalidwrote:
On Mon, 30 Jun 2008 11:47:45 -0500, Stephen Sprunk wrote:
kid joe wrote:
I'm using a temporary buffer to transfer some data and would rather
not allocate it on the heap.
why?

void process_stuff (size_t buffer_size)
{
char *buffer;
if ((buffer = malloc(buffer_size)) == NULL)
exit (EXIT_FAILURE);

do_stuff(buffer);
free(buffer);
}

The problem is that the size of the
buffer is only known upon entry into the function that utilizes it and
I'd rather not waste space or dynamically allocate on the heap (since
it doesn't need to persist).
malloc()ed stuff doesn't have to persist.
Now I'm planning on utilizing inline
assembly to modify the stack pointer directly to allocate the space I
need.
that *really* sounds like you're going to use assembler...

Here's an example:
void doSomeStuff(unsigned size) {
char* rawData;
//INLINED (Intel p4 assembly)
//sub esp, dword ptr [size]
//mov dword ptr [rawData], esp

//do some stuff with the temporary buffer, using rawData to access
it
//INLINED (Intel p4 assembly)
//add esp, dword ptr [size]
}
This should just work, right? Or are there any odd quirks that I should be
aware of that I may not have thought of?
Well, assuming you want to limit your code to only working on a
particular platform or processor, and you know your code won't conflict
with the compiler's optimizations...
malloc()/free() should be fast enough, even if it doesn't "feel" like
the right tool for the job.
hello! Did you read that bit!
If not, can you use a VLA?
or this?

If not, does
your system offer alloca()? Any of those are better than subverting the
compiler (and portability) and confusing people who will read your code
later by using inline assembly.
note alloca() is non-standard, often not implemented and often buggy.
Read some Unix man pages. Why use a buggy non-portable solution when
a portable solution (malloc()) is available? is malloc() too slow?
Is malloc() not available? Are you afraid of fragmentaion?

Thanks for the replies! After doing some research, I can confirm that this
is a solution that most C compilers support (pretty much 99% of all
compilers in current use today).
show your figures.

void *alloca(size_t size) - allocates a block of <sizebytes on the
stack from and returns a pointer to the start of the block, the block
is automatically freed upon return from the function it was called in
(in most implementations)
AND IT'S OFTEN BROKEN

Here's a slightly informative documentation of one compiler's
implementation:http://www.datafocus.com/docs/man3/alloca.3.asp

Note that anyone using this should investigate how their compiler
implements alloca(), as it can get sticky when using it within loops
and if statements (due to scoping). Some compilers will release the
memory upon leaving scope (loop-safe), while others will release the
memory upon leaving the function it is called in (can cause stack
bloating when used within loops).
so you have to do that every time you change compilers.
Maybe every time you upgrade the compiler or library...

Note alloca is sometimes in conflict with the compiler
Hope this is helpful for all those who may want to do the same thing.
This function was what I was exactly looking for - rather than
complaining about this being off topic, infer based upon what I was
trying to do that I was looking for C solution to stack allocation and
was going towards the inline assembly route.
but WHY
From the poor ability of inference in here, it seems the majority of
you would be better suited for the legal profession rather than
engineering profession - I've seen similar attitudes in many posts
here, whats the deal with trying to be as useless as possible
well to me it looks like you have the poor engineering approach.
You reject a solution out of hand and would rather use non-portable
functions than standard ones. There's a reason alloca() isn't in the
standard library.

I've never understood the "Oh please help me. Oh you are stupid"
attitude.
--
Nick Keighley
Jul 2 '08 #10
On Mon, 30 Jun 2008 11:06:52 +0200, Wolfgang Draxinger wrote:
>No need for inline assembler, if there's some portable function,
that will do the trick. However I can only advise, not to use
it. Most implementations of malloc are efficient enough to
compete in performance with...

alloca
The following (not particularly elegant) solution provides an
optimization for some cases. It uses two functions with automatic
arrays (one should be sufficient in practice) and one with dynamic
allocation.
static void doSomeStuffImp(char* buf, unsigned size) {
// implementation
}
static void doSomeStuff256(unsigned size) {
char buf[256];
doSomeStuffImp(buf, size);
}

static void doSomeStuff1024(unsigned size) {
char buf[1024];
doSomeStuffImp(buf, size);
}

static void doSomeStuffMalloc(unsigned size) {
// ...
}
void doSomeStuff(unsigned size) {
if(size <= 256) {
doSomeStuff256(size);
} else if(size <= 1024) {
doSomeStuff1024(size);
} else {
doSomeStuffMalloc(size);
}
}

--
Roland Pibinger
"The best software is simple, elegant, and full of drama" - Grady Booch
Jul 2 '08 #11

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

Similar topics

14
by: Kevin Grigorenko | last post by:
Hello, I couldn't find an obvious answer to this in the FAQ. My basic question, is: Is there any difference in allocating on the heap versus the stack? If heap or stack implementation is not...
9
by: Tom | last post by:
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.
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...
25
by: Brian Lindahl | last post by:
I'm using a temporary buffer to transfer some data and would rather not allocate it on the heap. The problem is that the size of the buffer is only known upon entry into the function that utilizes...
6
by: Chance Hopkins | last post by:
Can anyone tell me in a few words, is one of the following better and if so which one and why: if(varone != null) if(varone != "") dosomething(); if(varone != null && varone!= "")...
16
by: sarathy | last post by:
Hi all, I need a few clarifications regarding memory allocaion in C++. I apologize for the lengthy explanation. 1. In C++, Objects are allocated in heap. What does heap refer to? Is it an area...
5
by: sunny | last post by:
Hi All Is there any way to determine stack and heap size, during runtime. i.e can we predict stack overflow. etc
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...
87
by: CJ | last post by:
Hello: We know that C programs are often vulnerable to buffer overflows which overwrite the stack. But my question is: Why does C insist on storing local variables on the stack in the first...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

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.