home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!igor!thor!rmartin
- From: rmartin@thor.Rational.COM (Bob Martin)
- Newsgroups: comp.lang.c++
- Subject: Re: can I 'delete' without a 'new'?
- Message-ID: <rmartin.715714307@thor>
- Date: 5 Sep 92 17:31:47 GMT
- References: <1992Sep4.171020.4762@kentrox.uucp>
- Sender: news@Rational.COM
- Lines: 55
-
- peter@kentrox.uucp (Peter Uchytil) writes:
-
- |class foo {
- | char *String;
- |public:
- | foo();
- | foo( char * );
- | ~foo();
- | void set( char * );
- |};
-
- |foo:foo() { };
-
- |foo:foo( char *inString ) {
- | String = new char[strlen( inString )];
- | strcpy( String, inString );
- |}
-
- |void foo:set( char *inString ) {
- | String = new char[strlen( inString )];
- | strcpy( String, inString );
- |}
-
- |foo:~foo() {
- | delete [] String;
- |}
-
- |The question is what will happen if I create a foo with the empty constructor
- |and never call 'set'? Since 'new' has never been called, what will 'delete'
- |try to delete? Looks like a real good way to frazzle the system. Yes? No?
-
- It is, if the member variable String is non-zero. But if your default
- constructor sets this variable to zero, then the 'delete' in the
- destructor will be safe. Operator delete is well-behaved when passed
- a 0 argument.
-
- |Summary of questions:
- | 1) What happens if I call 'delete' without having called 'new'?
-
-
- If the pointer is zero, then nothing bad happens. If the pointer is
- non-zero then system frazzling is imminent.
-
- | 2) What happens if I call 'new' twice in a row? Sounds like I'm going
- | to make some memory become unrecoverable.
-
- The memory allocated by the first call to new would "leak" out of your
- application. You would never be able to put it back in the heap.
-
-
- --
- Robert Martin Training courses offered in:
- R. C. M. Consulting Object Oriented Analysis
- 2080 Cranbrook Rd. Object Oriented Design
- Green Oaks, Il 60048 (708) 918-1004 C++
-