bug-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Bug or undefined behaviour?


From: Daniel Junglas
Subject: Bug or undefined behaviour?
Date: Tue, 9 Mar 2004 10:24:32 +0100 (CET)

Hi all,

consider the following program self-assign.cpp
        #include <string>
        #include <iostream>

        int main (int argc, char** argv)
        {
          std::string const s =
            (argc == 2) ? std::string(argv[1]) : s;

          std::cout << s.c_str() << std::endl;

          return 0;
        }
I can compile it without warnings using 'g++ -W -Wall'.
When I run the program with one argument everything is fine. However, when
I run the program without any arguments I get a segmentation fault. The
problem seems to be the assignment of 's' to itself in the ternary
expression. I know that I should not write code like above but I
accidently ran into that problem. Is it a bug in g++ or is it just
undefiend behaviour (I do not have a C++ standard here to check that).
In my opinion the compiler should at least warn about this stuff.

My system is debian:
  g++ --version -> 3.0.4
  uname -a      -> Linux fb04383 2.4.24-2-686 #1 Wed Feb 25 21:46:26
                   EST 2004 i686 unknown
The backtrace of gdb is
  GNU gdb 2002-04-01-cvs
  Copyright 2002 Free Software Foundation, Inc.
  GDB is free software, covered by the GNU General Public License, and you
  are
  welcome to change it and/or distribute copies of it under certain
  conditions.
  Type "show copying" to see the conditions.
  There is absolutely no warranty for GDB.  Type "show warranty" for
  details.
  This GDB was configured as "i386-linux"...
  (gdb) r
  Starting program: /home/junglas/bugs/self-assign

  Program received signal SIGSEGV, Segmentation fault.
  0x0804c793 in std::char_traits<char>::assign(char&, char const&) (
      address@hidden, address@hidden)
      at /usr/include/g++-v3/bits/char_traits.h:142
  142           { __c1 = __c2; }
  (gdb) bt
  #0  0x0804c793 in std::char_traits<char>::assign(char&, char const&) (
      address@hidden, address@hidden)
      at /usr/include/g++-v3/bits/char_traits.h:142
  #1  0x0804a843 in std::string::c_str() const (this=0xbffff794)
      at /usr/include/g++-v3/bits/basic_string.h:717
  #2  0x0804a4c8 in main (argc=1, argv=0xbffff814) at self-assign.cpp:9
  (gdb)

Thanks for any comments

        Daniel





reply via email to

[Prev in Thread] Current Thread [Next in Thread]