C++ question

Daniel Dodson danield at cs.rhul.ac.uk
Sun Feb 10 18:00:19 PST 2002

The executable it produces should give that error. I've just compiled the
code you gave on my x86 Linux box and it is also segmentation faulting.
The lines 'p = k;' (using a shallow copy constructor) and 'p = person
("Bob", 10);' (shallow copying a temporary structure) are causing the
problems you are seeing. Because of char array you need a deep copy
constructor and also you'll need to overload the '=' operator. Otherwise
all you are doing is copying the memory address of the string. When main
goes out of scope the destructors are called. The name will effectively be
deleted twice in either case which is bad and will cause a segmentation
fault just like the following code will.

int main()
  char* pointer;
  pointer = new char[5];
  delete pointer;
  delete pointer; // intentional for the point I'm making



On Mon, 11 Feb 2002, [iso-8859-1] Christian Flöter wrote:

> Hi GCC users,
> I've tried this little C++ source which I found on the net. It compiles
> and links OK (Unixlib), but when run, it aborts. I'm using GCC 2.95.4 on
> a SARPC/RO3.7.
> Apart from this example, GCC works fine for me.  What's wrong here?
> Greetings,
> --
> Christian. <cfloeter at gmx.de>  http://lightning.prohosting.com/~cfloeter

More information about the gcc mailing list