segmentation violation due to unnoticed invalid code ?
Alexandre Oliva
oliva@dcc.unicamp.br
Tue Apr 13 14:29:00 GMT 1999
On Apr 13, 1999, Luc.Maisonobe@cnes.fr (Luc Maisonobe) wrote:
> I have encountered a problem with egcs 1.1.2 using delete. A
> segmentation violation occurs in glibc 2.0.7.
Which is fine, since your code invokes undefined behavior. Be happy
that it didn't try to kill you :-D
> After some investigation, it seems to me that I wrote invalid code but
> the compiler didn't noticed it.
I couldn't/shouldn't.
> A *a = new A [1];
> delete [] ((void *) a);
When you new an array, you must delete[] it using a pointer of the
actual type of the array elements. Since A is not void, the behavior
is undefined.
It turns out that delete[]ing a void* just calls free() with the
pointer given to it, whereas delete[] an A* would find out the size of
the array, that's stored just before the first object type, destruct
the array elements, and then free() the whole memory region, that
starts with the size. So, by delete[]ing the void* you're asking gcc
to call free() with a pointer that wasn't returned by malloc.
> Of course this is weird code (it has been corrected since then), but I
> would suggest egcs should complain about freeing an anonymous pointer.
Yep, it would probably be a nice feature, since `delete[] (void*)foo'
can *never* be well-defined behavior, as `new void[n]' is ill-formed.
--
Alexandre Oliva http://www.dcc.unicamp.br/~oliva IC-Unicamp, Brasil
{oliva,Alexandre.Oliva}@dcc.unicamp.br aoliva@{acm.org,computer.org}
oliva@{gnu.org,kaffe.org,{egcs,sourceware}.cygnus.com,samba.org}
*** E-mail about software projects will be forwarded to mailing lists
More information about the Gcc-bugs
mailing list