Bug in c_str()

With this code:

void bug5()
{
  string s = "one";
  cout<<("two[0]>"+s).c_str()<<endl;
}

I get:

The problem occurs only when character ‘>’ is after ‘[’ or ‘]’.

Hi,

I can indeed reproduce this problem. However there is a simple (C++ legal and recommended :slight_smile:) solution: do not call c_str() :slight_smile::

void bug5() { string s = "one"; cout<<("two[0]>"+s)<<endl; }works in both interpreted and compiled code and does exactly what you wanted :slight_smile:

Cheers,
Philippe.

Hello Philippe,

Thanks for reply.
The above example was just simplest program to reproduce this bug.
In real life I want to do something more useful:

for(int i=0; i<10; i++){
  TCut cut1 = ("tab[0]>"+toString(i)).c_str();
  tree->Draw("var",cut1);
}

Where “toString()” is a function which changes int to string:

template<typename T> std::string toString(const T& x) 
{ 
  std::ostringstream oss; 
  oss << x; 
  return oss.str(); 
}

As you see I need to use c_str() because constructor of TCut needs const char* instead of string.

In this case use a intermediary variable:

for(int i=0; i<10; i++){ std::string temp = ("tab[0]>"+toString(i)); TCut cut1 = temp.c_str(); tree->Draw("var",cut1); }

Cheers,
Philippe

Hi,

Yes it works… almost :slight_smile:

template<typename T> std::string toString(const T& x) 
{ 
  std::ostringstream oss; 
  oss << x; 
  return oss.str(); 
}

void bug6()
{
    for(int i=0; i<2; i++){
    string temp = ("var1/var2"+toString(i)+"&&var2/var3"+toString(i));
  }
}

When I run first time above program it is ok, but when I run it second time then it gives error:

Any idea?

Hi,

You are unfortunately tickled one of the known issue with CINT’s handling of the temporary objects. We will address this issue (and many other :slight_smile:) once we have completed CINT merge with Reflex. In the meantime, you can either simplify the expression or simply add a few #include statement and load your script via ACLiC (.L myscript.C+)

Cheers,
Philippe