Skip site navigation (1)Skip section navigation (2)
Date:      Mon, 18 May 2015 13:55:07 +0200
From:      Polytropon <freebsd@edvax.de>
To:        gyliamos@gmail.com
Cc:        freebsd-questions@freebsd.org
Subject:   Re: Strange return codes from old but good C program
Message-ID:  <20150518135507.ada90d25.freebsd@edvax.de>
In-Reply-To: <slrnmlhru5.190.varro@anukis.local>
References:  <20150517204503.V69409@sola.nimnet.asn.au> <20150517124223.GA82704@ozzmosis.com> <5558A2D0.8080207@hiwaay.net> <20150517171713.09b01ec4.freebsd@edvax.de> <slrnmlhru5.190.varro@anukis.local>

next in thread | previous in thread | raw e-mail | index | archive | help
On Sun, 17 May 2015 19:45:09 +0000 (UTC), Will Parsons wrote:
> I don't have the actual C standard, but Harbison & Steele's "C - A
> Reference Manual" (which I think can be relied on) states "If the end
> of the body of *main* is reached without returning, it is treated as
> if *return 0;* were executed".

In that case, no random return codes should appear. It also
doesn't meet the little test I've wrote (which again matches
with the initially described problem).

I have written (haha) the following "test case":

% cat returntest.c
main() {
        int i, j;
        for(i = 0, j = 0; i < 100; i++)
                j += i;
}

There are two "error" in it: main() doesn't have a return
type assigned, so per standard (int) will be assumed. And
there is no return statement.

Compiler is system's gcc (older system, obviously):

% cc -Wall -o returntest returntest.c 
returntest.c:1: warning: return type defaults to 'int'
returntest.c: In function 'main':
returntest.c:5: warning: control reaches end of non-void function

This is what we expect.

But the program can be run, and we see:

% ./returntest ; echo $?
99

The return code is somehow assigned to the 'i' variable.
Why? Probably because it's stored in a register, and this
register is being used by the exit() and _exit() chain to
represent the return code.

Funnily, when the program is modified:

main() {
        int i, j;
        for(i = 0, j = 0; i > -100; i--)
                j += i;
}

The compiler warnings are the same. This is the result now:

% ./returntest ; echo $?
157

None of them looks like an implicit "return 0;". I am not
judging Harbison & Steele, I'm just observing things. :-)



-- 
Polytropon
Magdeburg, Germany
Happy FreeBSD user since 4.0
Andra moi ennepe, Mousa, ...



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20150518135507.ada90d25.freebsd>