delete char * - why does it work

P

puzzlecracker

interesting case:

class MyString{
char * strRep; // initialized to char array

public:
~MyString(){delete strRep;} //why would this work
// just like 'delete [] strRep;'
};


isn't delete first calls the destructor for the object and then
deallocates the memory (by operator delete)?
 
J

Jonathan Mcdougall

puzzlecracker said:
interesting case:

class MyString{
char * strRep; // initialized to char array

public:
~MyString(){delete strRep;} //why would this work
// just like 'delete [] strRep;'

It doesn't if strRep was allocated with new[]. It does if strRep was
allocated with new.

char *c = new char[10];
delete c; // error

char *c = new char;
delete c; // ok

That's undefined behavior. On my system, mismatched new and delete
crashes almost everytime.


Jonatha
 
J

Jonathan Mcdougall

puzzlecracker said:
let's say it is allocated as char *c ="dummy";

IT WILL WORK!

Please quote what you are answering to next time.

Depends on what you mean by 'it will work'. If you intend to crash your
system, it may or may not work. If you intend to run into undefined
behavior, it will work. If you intend to have a well-behaving program,
it won't. Deleting something you haven't allocated yourself is illegal.


Jonathan
 
J

John Carson

puzzlecracker said:
the behavior is undefined - but why does it work on all compilers?????

I doubt that you have tested all compilers.

You really need to get over this nonsense. Undefined means that anything can
happen. Included in the "anything" is that it might work as you expect.
There is no explanation in standard C++ as to why something with undefined
behaviour might "work". That all depends on the details of compiler
implementations etc. If you want to know, then go ask the authors of the
compiler.

If you write correct code, you are entitled to expect it to work. If you
write code that invokes undefined behaviour, you have no right to expect
anything. The fact that code with undefined behaviour sometimes works in the
way expected by the programmers who write it is neither new nor interesting
information. Programmers who rely on such "good fortune" are fools.
 
J

Jakob Bieling

puzzlecracker said:
the behavior is undefined - but why does it work on all compilers?????


It does not. Proof? Try VS 7.1 on Win XP SP2 with:

class MyString
{
char* strRep;

public:
MyString (char* t) : strRep (t)
{
}

~MyString ()
{
delete strRep;
}
};

MyString s = "test";
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top