C++ strings causing crash?

I wrote a short function to produce a format string for sscanf while reading some ascii files into ROOT. It will load perfectly fine with either cint or ACLiC. The code below will enter the while loop, but will only execute the loop twice. On the third time through it will crash ROOT and dump core. It runs without complain when compiled in gcc. Any suggestions?


using namespace std;

// Produces a format string for sscanf()
const char* linef(int numave)
string line_f, temp;
line_f = “%f”;

int y;
y = 2;

while(y <= numave+5)
line_f = line_f + " %*f";

line_f = line_f + " %f";

return line_f.c_str();

Since you created your string on the stack you can’t return its internal (it is deleted/destroyed at the end of the function!).


string linef(int numave) { string line_f, temp; .... return line_f; }


Thanks, that turned out to be a problem and I did correct it. However, it still didn’t fix the specific problem I was seeing previously. I modified the original function to this:

[code]string linef(int numave)
string line_f;
const string beg = “%f”;
const string mid = " %*f";
const string end = " %f";
line_f = beg;

for(int y = 2; y <= numave+5; ++y)
line_f += mid;

line_f += end;

return line_f;

I’m not sure why the other modifications were necessary, but they appear to allow it to execute without incident.