Mail Archives: djgpp/2000/09/17/09:00:22
Thank You very much :-)))
Użytkownik Jack Klein <jackklein AT spamcop DOT net> w wiadomooci do grup
dyskusyjnych napisał:i3zEOX02JyFsEFt0MbK72k1ScoTo AT 4ax DOT com...
> On Sun, 17 Sep 2000 10:00:28 +0200, "Rafał Maj" <r_maj AT poczta DOT onet DOT pl>
> wrote in comp.os.msdos.djgpp:
>
> > Hi,
> > because my last question about delete / delete[] caused big discusion
with
> > meany diffrent opinions, I wan't to check, if finaly I understand it...
> > (probably not ;)
> > 1) "s" is a pointer to array, maked like: myclass* s = new
myclass[100];
> > a) delete []s will not only free memory, but alsow call
destructor
> > for each of 100 objects "myclass"
>
> Yes, that is correct.
>
> > b) using delete s; is probably wrong, because none destructor will
be
> > called. But all memory 100*sizeof(myclass) will be freed ?
>
> Maybe, maybe not. The C++ language standard states that items created
> with new[] be destroyed by delete[], and those with new by delete.
> Combining new[] with delete or new with delete[] is undefined
> behavior, which means anything can happen. Even if this happens to
> work with one particular, it might not with the next one.
>
> > 2) with char *s = new char[100] I can use :
> > a) delete []s; but it isn't necessarly, when char doesn't have any
> > destructor
> > b) delete s; is good
>
> No, delete after new[] is not good. It is illegal code, it is a bug,
> it is not valid C++. Even if it seems to work.
>
> > 3) and what with char* s = malloc(sizeof(char)*100); ?
>
> Actually you can't even compile this as C++, although you can as C.
> In C++ you can't assign a void * to another type of pointer without a
> cast. And you never, never need to multiply anything by sizeof(char),
> since sizeof(char) is 1 by definition, and always will be. The safest
> way to use malloc() is:
>
> char *s = (char *)malloc(100 * sizeof *s);
>
> In C, don't use the (char *) cast.
>
> > a) free - typical
>
> Yes, or realloc() with a size of 0.
>
> > b) can I use delete ?
>
> No.
>
> > c) can I use delete [] ?
>
> No.
>
> > 4) because strdup() uses malloc, char *s=strdup(S); should be
"deleted"
> > same way as in question 3
> >
> > Many Thanks,
> > Rafal
>
> There are three pairs of memory management functions, and you should
> never, NEVER, mix them:
>
> new & delete
> new[] & delete[]
> malloc() or calloc() & free()
>
> You can use all of these different methods in the same program for
> different allocations, but for any given memory block you must free it
> with the corresponding type you used to allocate it.
>
> Jack Klein
> --
> Home: http://jackklein.home.att.net
- Raw text -