From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (qmail 23202 invoked by alias); 7 Feb 2006 12:52:50 -0000 Received: (qmail 23189 invoked by uid 48); 7 Feb 2006 12:52:48 -0000 Date: Tue, 07 Feb 2006 12:52:00 -0000 Message-ID: <20060207125248.23188.qmail@sourceware.org> X-Bugzilla-Reason: CC References: Subject: [Bug libstdc++/26123] [3.4/4.0 Regression] Segmentation fault in constructor of std::ostream::sentry::sentry In-Reply-To: Reply-To: gcc-bugzilla@gcc.gnu.org To: gcc-bugs@gcc.gnu.org From: "broeni at osb-systems dot com" Mailing-List: contact gcc-bugs-help@gcc.gnu.org; run by ezmlm Precedence: bulk List-Archive: List-Post: List-Help: Sender: gcc-bugs-owner@gcc.gnu.org X-SW-Source: 2006-02/txt/msg00643.txt.bz2 List-Id: ------- Comment #9 from broeni at osb-systems dot com 2006-02-07 12:52 ------- Obviously the behavior of the test program is undefined. The following is the reply from Alberto Ganesh Barbati in c.l.c++.m Apart from the fact that you need to include in order to be able to write on std::cout, yes: it's well defined. However, its behaviour is unspecified. See below. > In particular: Does the standard guarantee that std::cout is > initialized before the constant `cInt'? No, the standard does not guarantee that (although it non-normatively encourages implementations to do it). According to ยง27.3/2: "The objects [std::cin, std::cout, etc.] are constructed, and the associations are established at some time prior to or during first time an object of class ios_base::Init is constructed, and in any case before the body of main begins execution." So in order to ensure that the program behave as expected, you need to construct a variable of type ios_base::Init before using std::cout. You can either use a global variable like this: int mkCint(); std::ios_base::Init gInitIostreams; const int cInt = mkCint(); or use a local variable in function mkCint(): int mkCint() { static std::ios_base::Init initIostreams; std::cout << "mkCint()" << std::endl; return 2; } Comment: While the use of a global variable works fine for the reduced test #2 the originally posted code (#1) only works with a local std::ios_base::Init in mkCint() because of the undefined initialization order of globals. The reply of James Kanze confirms the undefined behavior: > Is the following program well defined? > In particular: Does the standard guarantee that std::cout is > initialized before the constant `cInt'? No. With the classical implementation of , it was guaranteed IF your code included before defining cInt. Many (most?, all?) current implementations of also provide this guarantee, but the standard doesn't require it. -- http://gcc.gnu.org/bugzilla/show_bug.cgi?id=26123