WWaaarnniiing??!!

Hello.I get the warning

125 Z:\media\g_\fff\implementation.cpp [Warning] address of local variable `szreport' returned

at the following function

1
2
3
4
5
6
7
8
9
10
11
12
13
14
char*     Evaluation::show()
{
	char		szreport[2000]= "";
	char        szValue[7];

	strcat( szreport, "\n*****************************\n\tvalue:\t" );
    strcat( szreport, value );
	strcat( szreport, "\n\tdescription\t" );
    strcat( szreport, getDescription() );
    
    cout << szreport << endl;

 return szreport;
}


Could somebody please explain to me the cause for that warning?Thank you

szreport is an array local to the function. When the function returns, it goes out of scope ( and it's memory is automatically freed )
You are returning the address of that array which, after the function ends, will point to an invalid loacation
You can either allocate szreport with new/malloc or use a std::string
so, I shold write:

char* szreport = new char[2000]

true?
Yes, and then delete[] the returned pointer when you don't need it any more
sorry sir, when to delete[] it?
When you don't need it anymore.
or just use a string so you don't have to worry about overflowing the buffer / freeing the memory / etc.

1
2
3
4
5
6
7
8
9
10
11
12
13
// see how much easier this is?
//  it's also much, much safer and has no risk of memory leaks
string Evaluation::show()
    string  szreport;
    string  szValue;

    szreport = "\n*****************************\n\tvalue:\t";
    szreport += value;
    szreport += "\n\tdescription\t";
    szreport += getDescription();

    return szreport;
}
Last edited on
LB siad:

When you don't need it anymore.


in main(), what would the handle be thhen?
Disch (3168) Link to this post Sep 10, 2010 at 7:19pm


or just use a string so you don't have to worry about overflowing the buffer / freeing the memory / etc.


then there is difficulty with serializing it, I guess.
no there isn't?

why would serializing a char array be easier than serializing a string?
^^Isn't it?How?
how are you serializing the char array?

Odds are the string can be serialized the same way (or at least very similar)
Disch (3172) Link to this post Sep 10, 2010 at 8:09pm
how are you serializing the char array?

Odds are the string can be serialized the same way (or at least very similar)


using boost.Anyway I don't have the time to convert my entire program to a string version.Ii's 1000 lines of code.Please tell me about deleting after Newing it.it's less costly.
Last edited on
avoid doing the new/delete approach. Pass the array by pointer instead:

1
2
3
4
5
6
7
8
9
10
11
12
void Evaluation::show(char* szreport)
{
  // modify 'szreport' here
}


//...

char output[2000];
myeval.show( output );

cout << output;
why disch?

I thought arrays are passed by reference by default
They are.

But the point is, if you pass the pointer to the function you don't have to worry about scope issues like you do when returning a pointer.
Topic archived. No new replies allowed.