473,772 Members | 3,731 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

allocation of local variables on stack

Hi,

When you define varibles in the middle of your function call (C99),
such as:

if(i == 5) {
int x = 5;
int z = 2;
}

Are they allocated on the stack as they're encountered at run-time or
are they allocated before, along with the arguments and initial
variable declarations? Is a function activation record supposed to be
fixed before you start executing the function code (i.e. statements)?

If this is done at run-time, how does the (standard) compiler do it?

I have also heard about an alloca() call for allocating on the stack.
Is this a non-standard function? Is there a possibility of stack
overflow by doing this?

Thanks,
Bahadir

Nov 14 '05
26 2882
Keith Thompson wrote:
.... snip ...
There are functions available that will read a line of arbitrary
length from an input file, allocating it on the heap and expanding
with realloc() as necessary. If can be done portably, there's no
need, and no excuse, for code like the above.


Such as my ggets, freely available at:

<http://cbfalconer.home .att.net/download/ggets.zip>

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
Nov 14 '05 #21
>> Russell Shaw <rjshawN_o@s_pa m.netspace.net. au> writes:
Sometimes you don't know how much data you're going to read, so you
just have to plonk stuff on the stack regardless:

char* getfile(FILE *infile)
{
size_t i = 0;
char myarray[0];

while(!feof(inf ile)) {
myarray[i++] = fgetc(infile);
}

alloca(i);

char *buf = malloc(i);
memcpy(buf, myarray, i);
return buf;
}
Keith Thompson wrote:
Sorry, but that's just ugly.

It is worse than that: it does not even work, crashing right after
reading sufficiently long lines (even when using gcc on Linux on
an i386).
Apart from the misuse of feof() ...


Indeed.

In article <ac************ @main.anatron.c om.au>,
Russell Shaw <rjshawN_o@s_pa m.netspace.net. au> wrote:How about:

char* getfile(FILE *infile)
{
size_t i = 0;

while(!feof(inf ile)) {
char *ptr = alloca(sizeof(c har));
*ptr = fgetc(infile);
if(*ptr == EOF) {
return NULL;
}
}

char *buf = malloc(i);
memcpy(buf, ptr, i);
return buf;
}

This one has the advantage of "almost working" on some machines.

It still behaves very oddly on a SPARC. (Try it! It breaks even
on a SPARC running Linux, using gcc.)

The reason is that alloca() on the SPARC rounds the size up to
the nearest multiple of 8, as required by the architecture. Each
alloca(1) -- sizeof(char) is necessarily 1 -- allocates 8 bytes.
The text winds up strangely spaced.

It also fails when run on a few other, in another peculiar way: it
adds a mysterious '\377' character to the file. The reason is that
fgetc(infile) returns EOF, which is stored in *ptr, which has
type (plain) char, which is unsigned char. The test *ptr==EOF
compares 255 against -1; they are not equal and we make one more
trip through the loop. This time, feof(infile) is true -- because
the last fgetc() failed due to EOF -- and we believe that the
file ended with a '\377' byte.

It also fails mysteriously (on those machines) when run with input
redirected to a file that is on a floppy with a bad sector. This
time, it loops forever. The reason is that, as before, fgetc()
returns EOF, which is stored in the plain (and thus unsigned)
"char", and then we compare 255 vs -1, so we continue to loop.
This time, however, feof(infile) is false, because the failure was
due to an I/O error rather than EOF.

There are a number of "morals of the story", as it were. The main
two are:

Never use feof(). (For the advanced C programmer: "Well, hardly
ever.")

Do not depend on undocumented "features" like alloca() returning
contiguous bytes, because these are not always true.

Of course, there is a way to do this without using alloca() at all,
so that the code will work on any system supporting C89 or C99; but
if the goal is "to use alloca()", using only the standard C89/C99
features will not suffice, since alloca() is not one of them. :-)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Nov 14 '05 #22
CBFalconer wrote:
I'm leaping in here for two reasons. One is that you are a google
user who is using the system correctly, with adequate quotes etc.
So it IS possible. Congratulations , and it shows that we should
not automatically killfile all google users.
Thanks.
The other is the generic problem of off-topicness. This whole
thread is off-topic, yet where is the newbie to go?


Sorry about this. To be honest, I enjoyed the stack discussion, but I
must admit I didn't think enough to realise stacks were off-topic
before posting. I know how ugly it is when you see irrelevant/newbie
questions - I won't do it again.

Thanks,
Bahadir

Nov 14 '05 #23
pete wrote:
Russell Shaw wrote:
Keith Thompson wrote:

Even funnier.

char *ptr = alloca(sizeof(c har));
*ptr = fgetc(infile);
if(*ptr == EOF) {


If char is an unsigned type, then there's no way that
*ptr can equal EOF.


And if char is signed, then *ptr may equal EOF even though
the end of file has not been reached yet.

Also I don't see how the OP code could possibly work,
unless there's something about alloca nobody told me.
The next line of code was: memcpy(buf, ptr, i).

But ptr points to exactly one char, so if i>1 then he
is reading uninitialized memory. Also he has lost all
the chars he alloca'd in previous iterations of the loop.

Nov 14 '05 #24

Le 16/06/2005 00:58, dans
11************* *********@z14g2 00...legr oups.com, «*Old Wolf*»
<ol*****@inspir e.net.nz> a écrit*:
Also I don't see how the OP code could possibly work,
unless there's something about alloca nobody told me.
Apart from the numerous bugs, it could actually work,
but it is *highly* system- and compiler- dependant.
(and no need to say, highly non-standard).

char *tmp;
char *ptr = alloca(sizeof(c har));
int t;

for(;;) {
char *tmp = alloca(sizeof(c har));
t = fgetc(infile);
*tmp = t;
if(*tmp == EOF) {
...
}
i++;
}

This will work if alloca allocates contiguous bytes
on the stack, and the final memcpy will work
dependind on which direction the stack grows.
If you try that, check asm output, because it's
very likely that the produced executable won't
do what you expect. And don't use that in
production code in any circumstances :-)
The next line of code was: memcpy(buf, ptr, i).
But ptr points to exactly one char, so if i>1 then he
is reading uninitialized memory. Also he has lost all
the chars he alloca'd in previous iterations of the loop.


We have lost nothing: previous chars were allocated
on the stack and initialized. We assume we know were
they actually are (just after the first char allocated).
Nov 14 '05 #25

In article <11************ **********@g14g 2000cwa.googleg roups.com>, ba************@ gmail.com writes:
CBFalconer wrote:
The other is the generic problem of off-topicness. This whole
thread is off-topic, yet where is the newbie to go?
Sorry about this. To be honest, I enjoyed the stack discussion, but I
must admit I didn't think enough to realise stacks were off-topic
before posting.


IMO, the question as phrased was marginally on-topic, or perhaps just
the wrong side of topicality. There is to my mind a considerable
distance between "how are variables defined at inner scope allocated"
and, say, "how do I find out what's on my stack". The former is
something which conceivably might be (though in fact it is not)
covered by the standard, perhaps in some obscure fashion, while the
latter is clearly (to anyone who's taken a look at the standard
language features) implementation-specific.

Personally, I don't mind seeing questions about how language elements
are typically implemented, if they're posed well.

Another place for this sort of discussion is alt.folklore.co mputers,
where computing history is discussed. Unfortunately it's a relatively
high-volume group with a pronounced tendency to drift off-topic.
I know how ugly it is when you see irrelevant/newbie
questions - I won't do it again.


If all newbies were this careful with their posting style, I expect
there would be far less grumbling from the regulars.

--
Michael Wojcik mi************@ microfocus.com

Thus, the black lie, issuing from his base throat, becomes a boomerang to
his hand, and he is hoist by his own petard, and finds himself a marked man.
-- attributed to a "small-town newspaper editor in Wisconsin"
Nov 14 '05 #26
In article <dnFre.230$X71. 101@fed1read07> ,
Anonymous 7843 <an******@examp le.com> wrote:

int func(int a)
{
if (a > 0)
{
/* non-trivial return (usually) prevents tail-recursion elimination */
return other_func(a) * func(a-1);
}
else
{
struct gigantic_struct foo[1000000];
/* perform non-trivial processing of gigantic struct array */
/* return non-trivial value after processing */
}
}

Unless the compiler was particularly clever, it might grow
the stack at an alarming rate. I'll have to try this
one out with my favorite compilers and see what happens.


I tried this on three high quality compilers with full
optimization enabled. They each ate up the whole stack
within a few iterations.

I won't name names since this is probably not a valuable
thing to optimize in C. I was just curious.
--
7842++
Nov 14 '05 #27

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

Similar topics

6
8213
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 allocation to create object of that class ? 2. If it says "dynamic memory allocation", is it mean the following code : DestinationAddress* dest = new DestinationAddress(); // code 1
3
3339
by: asm | last post by:
Hello all, I need your help on this problem. I wrote a little program as follows. (BTW, I worked on a new dell latitude, runing Linux kernel 2.4.19, i686). Program was compiled with gcc 3.2 void foo() { char t; strcpy(t, "012345678901234567890123456789012345678");
34
2179
by: FMorales | last post by:
-- I didn't notice anything about this specifically -- in the c.l.c. FAQ, nor could i get a strait answere -- from my copy of the C standard. Hopeing someone -- here could shed some light on it :)... 6.2.1 "If the declarator or type specifier that declares the identifier appears inside a block or within the list of parameter declarations in a function definition, the identifier has block scope, which terminates at the
4
7237
by: gamja | last post by:
Hi all. I know that some padding bits are inserted between data members of a structure. Is this rule also applied for the variables on local stack or global??? For example, in following code dumps... ------------ struct foo foo1; .... struct bar bar1;
4
6630
by: veera sekhar kota | last post by:
I read structs are stored at stack area or inline-heap based objects. What is meant by inline-heap based objects? I didnt get that. Thanks, Veera.
2
2321
by: sandy | last post by:
Hi all, I tried compiling the above two programs : on x86, 32 bit machines. And when I used objdump on that I saw the following code. Can anyone help me know, Why in the objdump of our first program the esp is decremented by 18H bytes and in the second program the esp is decremented by 28H bytes.
53
26400
by: fdmfdmfdm | last post by:
This is an interview question and I gave out my answer here, could you please check for me? Q. What are the memory allocation for static variable in a function, an automatic variable and global variable? My answer: static variable in function and global variable are allocated in head, and automatic variable is allocated in stack. Right?
14
3837
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 this stored in stack. If yes whether it will be deleted on exiting from the function. is dynamic memory allocation needed for this purpose
5
1567
by: peridian | last post by:
Hello, I may be remembering incorrectly, but I'm sure that in C++ you could declare two variables of the same name where the second declaration is within it's own code block. E.g. void myfunction() { int x = 5; //some code
0
9620
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10261
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10038
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9912
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8934
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7460
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6715
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.