473,785 Members | 2,772 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

why does this work ?

Why does f get returned ? (compiled with gcc).

#include<stdio. h>

int func(int a);

main()
{ int f;
f=func(7);
printf("f=%d",f );

}
int func(int a)
{
int f,d = 100;
if (a<10){
f = d;
}
}

Ta,

Bamber.
Nov 13 '05
44 3282
On Sun, 12 Oct 2003 00:12:38 +0200, in comp.lang.c , Sidney Cadot
<si****@jigsaw. nl> wrote:
Hi Chris,
[[does the Standard require a stack?]]

The constraints in the standard force "stack-like behavior" for
local variables inside functions (including any parameters), and
I think it is not out of line to call this "a stack". [...]


As for me: If it walks like a stack and talks like a stack, so to say -
I'd prefer to call it a stack.


Except that its not. The standard doesn't require, or even force,
implementations to put variables into a stack. I don't think thats
what Chris was saying. For example all parameters could be (and even
on stack based machines generally are) passed via registers. All
automatics could be created in reserved memory, in no particular
order.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #11
Hi Barry,
[snip program]
As far as I can see, this is a perfectly valid C program that should
reach the 'return 0' statement always, were it not for the fact that in
It is valid in the theoretical sense but it executes in the real
world.
Of course I agree, but this being comp.lang.c, I think it's valid to
look at the ill-lit corners of the language as it is specified.

I mean, people here sometimes insist that code like:

#include <stdio.h>
int main(void)
{
int a[1];
printf("%d", a[1]);
return 0;
}

....could cause nuclear detonation or even (perish the thought!)
harddrive formatting, so I think there's a bit of a tradition with
regard to projecting theoretical issues onto practice.
All systems have limited resources. Even virtual memory is backed up
in some kind of file. I could not find in the standard a minimum for
the number of recursive function calls an implementation was required
to support. It does state that a function can be recursively called
at least once.
Of course you're right. I would be already half satisfied if there would
be a statement in the standard to the effect that "function calls are
allowed to consume an unspecified amount of an unspecified type of one
or more unspecified types of resources, which the function will release
upon completion of execution. Undefined behavior can occur when the
amount of said resources in use at any one time exceeds an unspecified
threshold."

The downside of such a statement of course would be that any program
performing function calls could cause undefined behavior. But right now
that seems to be an accurate representation of the state of affairs
anyway, so the question is: which one of the two evils is the most evil?

Please realize that I'm playing the devil's advocate here... I'm just
curious if I'm either missing something crucial in the Standard, or that
perhaps a wording could be found to mend the situation to the effect
that something real we sometimes observe in practice (stack overflows)
is covered by the Standard.
[[ some numbers on estimate of memory usage in the sample program ]]
The sample program was of course devised exactly to trigger a stack
overflow on any (or at least most) practical implementations .

An interesting point is that by recognizing tail recursion, a very smart
compiler could even come up with a translation that does, indeed,
eventually reach the 'return 0' statement.
Would you be asking your question if your program simply issued malloc
requests until no more memory was available? The only difference is
that malloc fails "politely" by returning NULL.
That's a good homologous case, yes, with the exception (as you point
out) that there is a perfectly good provision within the Standard to
handle it.
There doesn't seem to be any way for a recursion failure to be "polite." Both fail for
exactly the same reason. Only the symptoms of that failure are
different.
I beg to differ on your first statement, I think there is a way, but it
would require an amendment to the standard.

A function invocation could check if it would exceed the stack resource,
and (if so) abort execution, for example. This would require a change of
the standard, and would have performance ramifications. But it would be
possible.
Welcome to the limitations of practicality.


That's all good and dandy, but we still seem to be stuck in a situation
where a fully compliant program invokes a segmentation fault, which can
only signify undefined behavior (as the Standard doesn't talk about
segmentation faults). If that situation could be improved (and the point
of this discussion, for me at least, is to see if it can), I for one
would welcome it!

Best regards,

Sidney Cadot
The Netherlands

Nov 13 '05 #12
Hi Mark,
Is this 'incorrect behavior' of all these compilers, or is there some
wording in the Standard that covers for machines with a finite stack
(much to my dismay, this covers all machines I have access to)?
The C standard sets limits on the size, number and so forth of objects
that an implementation is required to provide. Infinite recursion, or
even relatively deep recursion, tends to break them. See 5.2.4 of the
Standard.


I've just browsed 5.2.4 of the Committee Draft dated August 3, 1998
(it's Saturday night after all - what else to do?).

5.2.4.1 gives some lower bounds on compile-time constructs a compiler
should be able to handle, and the other subsections give numeric
constraints that should be met.

I honestly see nothing in there that a program using infinite or
relatively deep recursion (such as my example) violates.

Best regards,

Sidney Cadot

Nov 13 '05 #13
Hi Arthur,
As for me: If it walks like a stack and talks like a stack, so to say -
I'd prefer to call it a stack.
But lots of non-pedants like to say things like, "automatic variables
are declared on the stack," or "the function parameters are pushed on
the stack in reverse order," or things like that -- which are blatantly
false, given some of the "stack-like" models that [whomever you were
quoting] demonstrated.
Ok. To clarify my understanding of this: the Standard sets forth a
number of constraints that amount to implementing an (abstract) stack,
that can be /though of/ as something on which things are pushed or
popped. The implementor is free to devise a way to implement this
abstract mechanism any way (s)he chooses.
If I understand what you're saying correctly, the standard does not (of
course!) force the underlying hardware to support anything stack-like,
but the runtime model implies something that can in good faith only be
called a stack ...or two stacks, or three. Or one three-element "stack" per function
(giving a maximum recursion depth of 3 calls). Or whatever else the
implementor comes up with...
Yes. I'm just not happy that the concept of a 'maximum recursion depth'
is brought in without any backing from the Standard.
[snip] That's interesting... Based on a literal reading of the standard at
least, I'd say my sample program is fully compliant and there's no
reason for it ever to not reach the 'return 0' statement. Correct. The only reason the program doesn't work is because we
live in the pesky physical world.
It's a drag, isn't it? :-) I would be happy to see this reflected in the
Standard.
To me, perhapse naively, this seems then like a point where the standard
is not complete. Anybody care to comment on that point of view?

Yup. The Standard doesn't give any hint of a min-max recursion depth.
In practice, I think most compiler systems use sensible recursion
strategies, limited only by the amount of RAM available. But yes, in
theory, all C compilers are non-conforming in this regard.
Surely the founding fathers of C99 have considered this issue(?) I
wonder if they couldn't come up with a good formulation, or decided it
was just not worth the effort.
You might be interested in this old thread: [...]


Thanks, I will go and read this. I used to toy with issues of Turing
completeness of different formal systems so this will make an
interesting read I'm sure.

Best regards,

Sidney Cadot

Nov 13 '05 #14
Hi Mark,
>[[does the Standard require a stack?]]
The constraints in the standard force "stack-like behavior" for
local variables inside functions (including any parameters), and
I think it is not out of line to call this "a stack". [...]


As for me: If it walks like a stack and talks like a stack, so to say -
I'd prefer to call it a stack.

Except that its not. The standard doesn't require, or even force,
implementations to put variables into a stack. I don't think thats
what Chris was saying. For example all parameters could be (and even
on stack based machines generally are) passed via registers. All
automatics could be created in reserved memory, in no particular
order.


I think the issue here is to distinguish between something that
/logically/ behaves like a stack, and something that is a classical
stack implementation as supported by many hardware platforms.

Reading Chris' reply I feel that his statement amounted to the effect
that, given the constraints in the Standard, it follows that an
implementation must support something that behaves like a /logical/ stack.

Your example of register based parameter passing hits home for me, as I
did some assembly coding on the PowerPC RISC architecture; parameter
passing by register is the preferred way of working there. However, when
doing recursive function calls where each invocation manages a local
state (dare I say: stack-frame), one is in effect emulating a /logical/
stack.

I'm curious about Chris' opinion on the matter, whether I did correctly
understand his reply.

Best regards,

Sidney Cadot

Nov 13 '05 #15
On Sun, 12 Oct 2003 01:09:01 +0200, in comp.lang.c , Sidney Cadot
<si****@jigsaw. nl> wrote:
5.2.4.1 gives some lower bounds on compile-time constructs a compiler
should be able to handle, and the other subsections give numeric
constraints that should be met.

I honestly see nothing in there that a program using infinite or
relatively deep recursion (such as my example) violates.


There are other min and max requirements scattered throughout the
standard as well, but, indeed, its probable that there's nothing to
specifically outlaw infinite recursion. Remember tho the standard is
notionally implemented in a theoretical machine. We live in the Real
World (tm) where infinite memory is not available.

--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #16
On Sun, 12 Oct 2003 01:21:39 +0200, in comp.lang.c , Sidney Cadot
<si****@jigsaw. nl> wrote:
But lots of non-pedants like to say things like, "automatic variables
are declared on the stack," or "the function parameters are pushed on
the stack in reverse order," or things like that -- which are blatantly
false, given some of the "stack-like" models that [whomever you were
quoting] demonstrated.


Ok. To clarify my understanding of this: the Standard sets forth a
number of constraints that amount to implementing an (abstract) stack,
that can be /though of/ as something on which things are pushed or
popped.


AFAIK No, the standard sets out no constraints that /require/ anything
to be pushed or popped from a stack, or even to amount to doing that.
Thats merely one way to represent what the standard requires which is
that for example copies of the values of the parameters to a function
be made available in the function, or that array members shall appear
to be adjacent in memory.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #17
On Sun, 12 Oct 2003 01:31:51 +0200, in comp.lang.c , Sidney Cadot
<si****@jigsaw. nl> wrote:
I think the issue here is to distinguish between something that
/logically/ behaves like a stack,


In what way does the standard /REQUIRE/ the logical behaviour of a
stack.

Thats as opposed to "S Cabot needs an internal mental picture of how
function calls etc work, and he finds the idea of a stack easy to
visualise and operate with". No offense intended.

For myself I don't need this mental picture. I think of function
calls, recurnsion and automatics as involving the computer storing
different data in various places, and remembering where it is at the
relevant time.

A bit like me working on something, and using various books from my
bookshelf. I feel no compulsion to make a "stack" of hte ones I need,
pushing the most recently used one to the top, and then popping it off
again when I'm done. I merely pull them off the shelf when needed, and
put 'em back afterwards, generally in much the same place but a few
books to the left or right doesn't matter, I'm no Dewey obsessive.
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
----== Posted via Newsfeed.Com - Unlimited-Uncensored-Secure Usenet News==----
http://www.newsfeed.com The #1 Newsgroup Service in the World! >100,000 Newsgroups
---= 19 East/West-Coast Specialized Servers - Total Privacy via Encryption =---
Nov 13 '05 #18
Hi Mark,
I think the issue here is to distinguish between something that
/logically/ behaves like a stack,
In what way does the standard /REQUIRE/ the logical behaviour of a
stack.
Well, in a very obvious way really. Actual parameters and local
variables are accessible during execution of a function; they become
inaccessible during a recursive call as the same formal parameters and
local variables now refer to new, independent variables, which cease to
exist upon return from the secondary call to the same function. I think
you will agree that this behavior is prescribed by the standard.

To me at least, this seems equivalent to viewing the set of parameters
and local variables as a tuple; the ordered list of these tuples
associated with recursive invocations of a function, of which only the
current one is accessible, has all the hallmark properties of a stack of
which only the top-most element is accessible at any given time.
Thats as opposed to "S Cabot needs an internal mental picture of how
function calls etc work, and he finds the idea of a stack easy to
visualise and operate with". No offense intended.
None taken, not even for misspelling my name ;-)
For myself I don't need this mental picture. I think of function
calls, recurnsion and automatics as involving the computer storing
different data in various places, and remembering where it is at the
relevant time.
My main argument in this thread is not whether C prescribes a logical
stack or not; for me that's a useful model (so good, in fact, that I
would be interested to see where this model falls apart), and for you it
isn't. That's A-ok by me.

On the risk of committing speculation, I think you would be hard-pressed
to find a compiler implementor who doesn't use the stack as a very
useful model while implementing a C (or any other) compiler.

What I /would/ like to get to is the phenomenon that a seemingly
standard-compliant program can exhibit undefined behavior. There's a
number of explanations (perhaps there are more):

* the standard does in fact cover this case through a specific limit
exceeded (for example) by my small program, and nobody mentioned
it so far in this thread.
* the standard does in fact cover this case, as it presumes an
idealized machine where certain practical constraints do not
hold (I'd welcome a clear reference).
* the standard does not cover this case.

Presuming for the moment that the third case is what's going on, I think
it is a worthwile exercise to ponder if/how the standard could be
amended in such a way as to cover this case. Stack overflow (perhaps
'resource depletion due to many nested function calls' is a better, but
clumsier term), in my opinion, is a phenomenon that is important enough
to deserve mention in the standard. I would be interested to know if
people disagree with this.
A bit like me working on something, and using various books from my
bookshelf. I feel no compulsion to make a "stack" of hte ones I need,
pushing the most recently used one to the top, and then popping it off
again when I'm done. I merely pull them off the shelf when needed, and
put 'em back afterwards, generally in much the same place but a few
books to the left or right doesn't matter, I'm no Dewey obsessive.


But then, you're not a running C program which, I hope, exhibits a level
of neurotic-obsessive behavior that would make a clinical psychiatrist
dance with joy.

Best regards,

Sidney Cadot

Nov 13 '05 #19
Chris Torek wrote:
Sidney Cadot <si****@jigsaw. nl> writes:
Joona I Palaste wrote:

There is no requirement for implementations to *have* a stack
in the first place.

This is the second time I see this posted over the last couple
of days, and you're surely right.


In a technical sense, at least, and it *does* matter sometimes.

The constraints in the standard force "stack-like behavior" for
local variables inside functions (including any parameters), and
I think it is not out of line to call this "a stack". But one
should remember that this "stack" may well be implemented as,
e.g., a linked list of frames:


I just came up with a new system that can confuse many programs
that take liberties. :-)

Assuming that byte, short, int, long are all an increasing size,
i.e. 1,2,4,8, and that we can fit float and double in there, lets
have a machine with 4 separate stacks, separated by size.

We can also have an assortment of sized registers, each of which
represents the top of a stack of items of its own size.

I think it would be a feasible machine. Might be a good basis for
the DS9000.

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!
Nov 13 '05 #20

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

Similar topics

7
4860
by: Jonas | last post by:
This works fine in Win XP but does not work at all in Win 98. Private WithEvents objIExplorer As InternetExplorer I have to do it like this to get it to work in Win 98 Dim objIExplorer As InternetExplorer But then I cant see when a user exit my objIExplorer and than an error will show up when I try to open a link in the IE window that does not exist... What can I do about this and way does it not work in win 98?
3
3743
by: Julian | last post by:
Hi I am trying to update a date field in my table but some how this simple code does not work, I know the select work because if I write the fields, it will show the data from the table but why the update does not work? <% Set ConnGallery = Server.CreateObject("ADODB.Connection") ConnGallery.Open ConnectionString Set cmdTemp = Server.CreateObject("ADODB.Command")
5
3641
by: me | last post by:
I have a Class Library that contains a Form and several helper classes. A thread gets created that performs processing of data behind the scenes and the Form never gets displayed (it is for debug puposes only and is not normally visable to the user.) The Thread function is actually in the Form class. Now.. What I am seeing is that when I create an instance of this Class Library's Form, which starts the worker thread, it seems to hose up...
22
2624
by: Robert Bralic | last post by:
CAN anybody tell me any address where I can download some small(1000-2000) lines C++ proghram source. Or send me ,a small(1000-2000) lines C++ program source that I can compille with gpp under Linux Suse 7.1. I can't belive that C++ exists. Thanks in advance ! robert.bralic@si.htnet.hr
12
2953
by: Frank Hauptlorenz | last post by:
Hello Out there! I have a DB2 V7.2 Database (Fix11) on Win 2000 Professional. It was before a NT 4 based Domain - now it is a Win 2000 Domain. The database server is a domain member. Now sometimes Win 2000 Clients can't connect to the database. They connect over TCP/IP. The db2log says that the function getHostByName failed. It seems to be only on new installed win 2000 Workstations. Already installed WS have NOT this problem.
0
2370
by: Jarod_24 | last post by:
How does tabindex work in ASP .net pages I dosen't seem to work quite like in regular forms. and there isn't any TabStop property either. 1 .How do you prevent a control form beign "tabbed". (hidden textboxes ect.) 2. How do get a control to get focus when the page is loaded (think username textfield on a loginpage) 3. Does the tab-order work just like in regular forms (1 ->2 -> 3 and so on?) 4. How does tabindex work with datagrid...
14
4863
by: Anoop | last post by:
Hi, I am new to this newsgroup and need help in the following questions. 1. I am workin' on a GUI application. Does C# provides Layout Managers the way Java does to design GUI? I know that it can be done using the designer but I intentionally don't want to use that. The one reason is that you cannot change the code generated by the designer. The other could be that you have more free hand and control to design your GUI. 2....
89
6079
by: Cuthbert | last post by:
After compiling the source code with gcc v.4.1.1, I got a warning message: "/tmp/ccixzSIL.o: In function 'main';ex.c: (.text+0x9a): warning: the 'gets' function is dangerous and should not be used." Could anybody tell me why gets() function is dangerous?? Thank you very much. Cuthbert
14
3495
by: webEater | last post by:
I have a problem, it's not browser specific, and I don't get a solution. I have an (X)HTML document, I show you a part of it: .... <!--<div class="pad">--> <div id="eventImages"><img src="" id="eventImage0" class="eventImage"><img src="" id="eventImage1" class="eventImage"></div>
1
7113
by: =?ISO-8859-1?Q?Lasse_V=E5gs=E6ther_Karlsen?= | last post by:
I get the above error in some of the ASP.NET web applications on a server, and I need some help figuring out how to deal with it. This is a rather long post, and I hope I have enough details that someone who bothers to read all of it have some pointers. Note, I have posted the stack trace and the code exhibiting the problem further down so if you want to start by reading that, search for +++ Also note that I am unable to reproduce...
0
9643
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
9480
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,...
1
10087
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
9947
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
6737
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();...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4046
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
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2877
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.