Simple function returns junky string

Started by
11 comments, last by silvia_steven_2000 18 years, 10 months ago
Quote:Original post by Genjix
correct me if I'm wrong but isn't it a bad thing if that variable is static and consumes memory throughout the whole program whether you use the function once or twice?


Yes, but that's not the reason it's really bad :-).

1) Using a global/static variable will force the variable in question to be commited to memory, and reread from memory, no matter what. This eliminates the ability for the compiler to simply pass by register certain values, which is bad from an optimization perspective, and worse yet, it has a good chance at cache thrashing when the function is run.

2) It's not thread safe (nor re-entrant (sp?)). The string can be modified while another thread is reading it, since you have a single copy for the entire program.

For char arrays, this can cause one thread to view another thread's string, or part of it's string and part of another thread's string.

For dynamically allocated strings, either via directly realloc()ing char pointers or by using std::string, this can result in reading allready "freed" memory which could be in use by another thread, causing absolute gibberish there. The program might even segfault.

[Edited by - MaulingMonkey on May 26, 2005 7:44:24 AM]
Advertisement
What you currently have doesn't work if you call the function more than once before having finished using the result of the last call.

Consider this:
std::string getChar(){    std::stringstream stream;    stream << 123;    return stream.str();}


It's clean, you don't have to worry about memory (either buffer overflows, or allocation/deallocation) and you can still get a char* if you want using std::string::c_str().
thanks all

This topic is closed to new replies.

Advertisement