Re: [ROOT] Problem with deletion of character array

From: Rene Brun (Rene.Brun@cern.ch)
Date: Sun Dec 15 2002 - 22:43:54 MET


Hi Christian,

What you do is illegal. When you delete tmpname, tmpname points
to a different address than the one at creation time.
Do something like
     TString outname = TString(name);
     char   *keepname = new char[strlen(name) + 1];
     char *keepname = tmpname;
     
     Int_t idx = 0;
     tmpname = strtok(strcpy(tmpname,name),sep);
     while(tmpname) {
        outname = tmpname;  
        if (idx == n) break;
        tmpname = strtok(NULL,sep);
        idx++;
     }//while
     
     delete [] keepname;

Rene Brun

On Sun, 15 Dec 2002, cstrato wrote:

> Dear Rooters
> 
> In order to extract variables from "const char *varlist",
> with e.g. varlist = "x:y:z:a", I have created the following
> function to get:
>     TString var1 = SubString("x:y:z:a", ":", 1);
>     TString var2 = SubString("x:y:z:a", ":", 2);
> 
> //-------------------------
> TString SubString(const char *name, const char *sep, Int_t n)
> {
>     // Extract substring from name at separator number n
> 
>     TString outname = TString(name);
>     char   *tmpname = new char[strlen(name) + 1];
> 
>     Int_t idx = 0;
>     tmpname = strtok(strcpy(tmpname,name),sep);
>     while(tmpname) {
>        outname = tmpname;
>        if (idx == n) break;
>        tmpname = strtok(NULL,sep);
>        idx++;
>     }//while
> 
>     delete [] tmpname;  //<======== Problem
> 
>     return outname;
> }//SubString
> //------------------------
> 
> However, often, I get the following error:
> *** malloc[416]: Deallocation of a pointer not malloced: 0x1b2d565;
> This could be a double free(), or free() called with the middle of
> an allocated block; Try setting environment variable MallocHelp to
> see tools to help debug
> 
> Can you tell me if I have to delete tmpname or not?
> Does the TString class offer me a better way?
> 
> Thank you in advance for your help.
> 
> Best regards
> Christian
> _._._._._._._._._._._._._._._._
> C.h.i.s.t.i.a.n S.t.r.a.t.o.w.a
> V.i.e.n.n.a       A.u.s.t.r.i.a
> _._._._._._._._._._._._._._._._
> 
> 



This archive was generated by hypermail 2b29 : Sat Jan 04 2003 - 23:51:23 MET