On Nov 19, 7:24 am, Jack Klein <jackkl...@spamcop.netwrote:
On Sun, 18 Nov 2007 22:29:54 -0800 (PST), singhraghvendra
<raghu.i...@gmail.comwrote in comp.lang.c++:
See the program below. I am trying to copy 20 bytes of data in a 10
bytes of buffer. The copy succeeds and also it displays the result
What do you mean by "succeeds"?
correctly. But the delete [] a1 fails and gives an error. Can anyone
point out the exact reason why delete fails.
What do you mean, "delete fails". What makes you think if fails? How
do you know that it fails?
Writing past the end of an array generates undefined behavior. There
is no "reason" why delete fails. Once you produce undefined behavior,
you are beyond the realm of the C++ language. The language does not
define, nor place any requirements on, the behavior of the program.
int main()
{
char*a1 = new char[10];
char* str20 = "12345678901234567890";
strcpy(a1,str20);
cout<<"a1: "<<a1;
delete [] a1;
}
There is no such thing as an "exact reason" when undefined behavior is
involved. Anything that happens is just as right or wrong as anything
else. You broke the rules, anything goes.
That said, of course, there is a reason why it "fails" in this case.
It's just implementation specific. The C++ spec allows the compiler/
runtime implementors to make certain assumptions about how correct the
code is. They've implemented the delete[] assuming that you have
respected the requirements of creating a dynamic array. It might be,
for instance, that the runtime is storing the size of the array that
you allocated at the memory at the end of the array. When you overflow
the array you overwrite the array size and when you delete the wrong
size is read back, the runtime tries to delete memory it doesn't own
and crashes. If you really want to know what's going on check the
compiled code.