home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!news.mentorg.com!sdl!adk
- From: adk@Warren.MENTORG.COM (Ajay Kamdar)
- Subject: Re: can I 'delete' without a 'new'?
- Message-ID: <1992Sep7.182055.8329@Warren.MENTORG.COM>
- Organization: Mentor Graphics Corp. - IC Group
- References: <1992Sep4.171020.4762@kentrox.uucp>
- Date: Mon, 7 Sep 1992 18:20:55 GMT
- Lines: 61
-
- In article <1992Sep4.171020.4762@kentrox.uucp> peter@kentrox.uucp (Peter Uchytil) writes:
- >I can't seem to find any references which indicate whether I can do this
- >or not, so I'm appealing to the net.wisdom. Here's what I've got:
- >
- >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 );
- >}
- >
- You have a severe bug in the above code. When you new a character array
- to hold a copy of the inString, you want to allocate space for ONE MORE
- than the length of the string (to hold the terminating '\0'). i.e.,
- String = new char[strlen(inString) + 1+;
- 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?
- >
-
- Yes, a real good way to frazzle the system. What you want to do is
- to set String to 0 in the default constructor as follows:
-
- foo::foo() : String(0) {}
-
- >
- >But then does 'set' first have to do a 'delete' before doing another 'new'?
- >I would assume it does.
- >
-
- Yes, you need to do a delete before doing a new in set().
-
-
- - Ajay
-
- --
- I speak for none but myself.
-
- Ajay Kamdar Email : ajay_kamdar@mentorg.com
- Mentor Graphics, IC Group (Warren, NJ) Phone : (908) 580-0102
-