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. 44 3281
Bamber <ba************ ******@yahoo.co .uk> scribbled the following: Why does f get returned ? (compiled with gcc).
It doesn't. You're mistaking implementation-dependent behaviour for
normal operation.
#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; } }
When control reaches the end of func(), the returned value is
indeterminate. When the assignment f=func(7) is done in main(), the C
implementation tries to get a value from where there isn't any. On
some implementations , this is the last value put on a stack before
the assignment happens, but there is no requirement that implementations
should do this. There is no requirement for implementations to *have* a
stack in the first place.
Generally, you just got (un)lucky.
--
/-- Joona Palaste (pa*****@cc.hel sinki.fi) ---------------------------\
| Kingpriest of "The Flying Lemon Tree" G++ FR FW+ M- #108 D+ ADA N+++|
| http://www.helsinki.fi/~palaste W++ B OP+ |
\----------------------------------------- Finland rules! ------------/
"Ice cream sales somehow cause drownings: both happen in summer."
- Antti Voipio & Arto Wikla
Greetings.
In article <37************ **************@ posting.google. com>, Bamber wrote: Why does f get returned ?
It doesn't. In fact, nothing gets returned, since there is no return
statement to be found anywhere in your program.
Regards,
Tristan
--
_
_V.-o Tristan Miller [en,(fr,de,ia)] >< Space is limited
/ |`-' -=-=-=-=-=-=-=-=-=-=-=-=-=-=-= <> In a haiku, so it's hard
(7_\\ http://www.nothingisreal.com/ >< To finish what you
In <37************ **************@ posting.google. com> ba************* *****@yahoo.co. uk (Bamber) writes: 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 );
There is a newline character missing in this format string. } int func(int a) { int f,d = 100; if (a<10){ f = d; } }
By pure accident. Your code invokes undefined behaviour, by using the
value returned by a function that doesn't actually return anything, so
*anything* can happen.
Compiled with the same compiler, on a diferent platform, the output is
different:
mentor:~/tmp 11> uname -a
SunOS mentor 5.8 Generic_108528-11 sun4u sparc
mentor:~/tmp 12> cat test.c
#include<stdio. h>
int func(int a);
main()
{ int f;
f=func(7);
printf("f=%d\n" ,f);
}
int func(int a)
{
int f,d = 100;
if (a<10){
f = d;
}
}
mentor:~/tmp 13> gcc test.c
mentor:~/tmp 14> ./a.out
f=7
This doesn't look like f's value before func() returns, does it?
By your logic, I should start asking myself: why does func() return the
value of its parameter? ;-)
Moral: it is a pure waste of time to try to understand why a piece of
broken code behaves the way it does.
Dan
--
Dan Pop
DESY Zeuthen, RZ group
Email: Da*****@ifh.de
Joona I Palaste wrote: <snip> 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. But it does beg the following question:
----
#include <stdio.h>
/* returns n! modulo 2^(number of bits in an unsigned long) */
unsigned long f(unsigned long n)
{
return (n==0) ? 1 : f(n-1)*n;
}
int main(void)
{
unsigned long z;
for(z=1;z!=0;z* =2)
{
printf("%lu %lu\n", z, f(z));
fflush(stdout);
}
return 0;
}
----
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
all compilers I tried (one, actually) it terminates with a segmentation
fault of some sort, due to limited stack size.
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)?
If so, is there a minimum depth of function calls that I can rely on to
be executed properly? I would hate to rewrite all my programs to do
everything within main() without function calls, for the ultimate
portability :-)
Best regards,
Sidney
In article <bm**********@n ews.tudelft.nl> ,
Sidney Cadot <si****@jigsaw. nl> wrote: #include <stdio.h>
/* returns n! modulo 2^(number of bits in an unsigned long) */ unsigned long f(unsigned long n) { return (n==0) ? 1 : f(n-1)*n; }
int main(void) { unsigned long z; for(z=1;z!=0;z* =2) { printf("%lu %lu\n", z, f(z)); fflush(stdout); } return 0; }
----
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 all compilers I tried (one, actually) it terminates with a segmentation fault of some sort, due to limited stack size.
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)?
If so, is there a minimum depth of function calls that I can rely on to be executed properly? I would hate to rewrite all my programs to do everything within main() without function calls, for the ultimate portability :-)
I suggest you start saving your money for a POWER4 with 64 GB of memory
or so, which IBM will happily sell you for some six digit dollar number.
Make sure that unsigned long is not more than 32 bit, though.
>Joona I Palaste wrote: There is no requirement for implementations to *have* a stack in the first place.
In article <bm**********@n ews.tudelft.nl>
Sidney Cadot <si****@jigsaw. nl> writes: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:
struct stackframe {
struct stackframe *inner;
unsigned char mem[]; /* C99 "flexible array member" syntax */
};
and the memory for each stack frame allocated out of a general
storage pool, so that there is no fixed addressing relationship
between any pair of stack frames. This is in fact the method used
on early IBM 370 C compilers. (I imagine it is still used on S/370
architectures, since there is no dedicated "frame pointer" register,
though as I recall R14 is somewhat conventional.)
Other hardware that runs C code may have two or more hardware
stacks, and/or multiple software stacks. Consider Moore's "Forth
on a chip" systems, which have a call/return stack separate from
their "value" stack on which one would pass parameters. Or look
at the Pyramid, which had separate "control" and "data" stacks,
although the control stack held register values which were often
(probably "usually") data.
... is there a minimum depth of function calls that I can rely on to be executed properly? I would hate to rewrite all my programs to do everything within main() without function calls, for the ultimate portability :-)
I have never found one. The "Translatio n limits" section (at or
near 5.2.4.1) is the logical place for something like "at least N
function activations down from the initial call to main()", but
there is no such wording. On the other hand, that section is not
a good weapon against Evil Compilers, as it requires only that an
implementation "translate and execute ... one program" that tests
those limits.
--
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://67.40.109.61/torek/index.html (for the moment)
Reading email is like searching for food in the garbage, thanks to spammers.
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.
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 (albeit perhaps one that implemented in software, as your
IBM 370 and other examples show). Interesting.
... is there a minimum depth of function calls that I can rely on to be executed properly? I would hate to rewrite all my programs to do everything within main() without function calls, for the ultimate portability :-)
I have never found one. The "Translatio n limits" section (at or near 5.2.4.1) is the logical place for something like "at least N function activations down from the initial call to main()", but there is no such wording. On the other hand, that section is not a good weapon against Evil Compilers, as it requires only that an implementation "translate and execute ... one program" that tests those limits.
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.
Now the actual behavior, segfaulting, is usually classified as a
manifestation of 'undefined behavior' in other contexts. Moreover, it is
obvious that one cannot sensibly expect arbitrarily deep function calls
to work (although the standard doesn't give limits).
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?
Best regards,
Sidney Cadot
The Netherlands
On Sat, 11 Oct 2003 12:53:07 +0200, in comp.lang.c , Sidney Cadot
<si****@jigsaw. nl> wrote:
snip prog that runs out of stack space 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.
--
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 =---
On Sun, 12 Oct 2003, Sidney Cadot wrote: [[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.
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.
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...
(albeit perhaps one that implemented in software, as your IBM 370 and other examples show). Interesting.
... is there a minimum depth of function calls that I can rely on to be executed properly? I would hate to rewrite all my programs to do everything within main() without function calls, for the ultimate portability :-) I have never found one. The "Translatio n limits" section (at or near 5.2.4.1) is the logical place for something like "at least N function activations down from the initial call to main()", but there is no such wording. On the other hand, that section is not a good weapon against Evil Compilers, as it requires only that an implementation "translate and execute ... one program" that tests those limits.
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.
Now the actual behavior, segfaulting, is usually classified as a manifestation of 'undefined behavior' in other contexts. Moreover, it is obvious that one cannot sensibly expect arbitrarily deep function calls to work (although the standard doesn't give limits).
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.
You might be interested in this old thread: http://groups.google.com/groups?
th************* *************** *************** *@unix47.andrew .cmu.edu
which is also continued under different subject lines here: http://groups.google.com/groups?
threadm=Pine.LN X.4.53L-031.03042513022 60.9612%40unix4 4.andrew.cmu.ed u
th************* *****@news.mega netnews.com
and several other places. [I hate the way Google Groups handles
threads with changing subject lines!] Search for "C turing-complete"
in comp.programmin g and comp.lang.c, and see what pops up, if you're
still interested. (Bottom line: An infinite stack can't simulate an
infinite tape.)
-Arthur This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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?
|
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")
|
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...
|
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
|
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.
| |
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...
|
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....
|
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
|
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>
|
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...
|
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,...
| |
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...
|
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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,...
|
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();...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |