Sign in to follow this  
silvia_steven_2000

Simple function returns junky string

Recommended Posts

(1) why does the function below returns a junk string instead of "123" ?! const char* getChar() { char buf[5]; sprintf(buf, "%d", 123); std::string s = buf; return s.c_str(); } (2) how to make the function return the string as wchar_t ? thanks for your help

Share this post


Link to post
Share on other sites
Guest Anonymous Poster   
Guest Anonymous Poster
Ask yourself what happens to the local function variable std::string s when you exit from the function and function scope?

Hint: s gets stored on the stack when the function begins.

Hint2: s.c_str() points to memory within the s variable

Share this post


Link to post
Share on other sites
snk_kid    1312
Quote:
Original post by silvia_steven_2000
(1) why does the function below returns a junk string instead of "123" ?!


because "s" is a local variable and is automatically deleted when the function's scope ends.

Quote:
Original post by silvia_steven_2000
(2) how to make the function return the string as wchar_t ?


std::string is a type alias for std::basic_string which is class template typedef'ed with char and defaults to using std::char_traits<char>, there exists another type alias for wchar_t known as std::wstring.

Share this post


Link to post
Share on other sites
Decibit    140
(1) a. use global variables
or b. declare your local variables as static

(2)
You need to convert the string to unicode first. Standard C library function "mbtowc" does it.
An example:

static wchar_t wbuf[5];
mbtowc(wbuf,buf,5);
return wbuf;

Share this post


Link to post
Share on other sites
persil    199
Return a std::string instead of char *. Or std::wstring (I think it,s the right name), if you want wide-chars.

Share this post


Link to post
Share on other sites
Zahlman    1682
Quote:
Original post by persil
Return a std::string instead of char *. Or std::wstring (I think it,s the right name), if you want wide-chars.


Quoted for being the right answer. Do the conversion on the receiving end, and only if you really have to. Better yet, stick with std::string basically everywhere else in your program, and wrap calls to library functions expecting/returning char*. For example:


char* LibraryFunction(char* input);
// possibly modifies the pointed-to data, but obviously cannot change the 'input'
// pointer itself, since it's a C function and thus there's no pass-by-ref.

std::string wrapper(std::string& input) {
// create a mutable copy of the string data
char* tmp = new char[input.length() + 1];
// If the library function ends up writing beyond that allocation, then it's
// the library's fault :P Meanwhile, std::strings can contain embedded \0's,
// but the library probably wouldn't handle those properly *regardless*.
strcpy(tmp, input.c_str());
// Call function on the buffer and save result
char * result = LibraryFunction(tmp);
// Wrap both buffers into strings and return appropriately
input = tmp;
return std::string(result);
}

Share this post


Link to post
Share on other sites
declaring the variable as static works fine and makes the function return a non junk value but still I can not convert the char* to wchar_t*. how is that done ?

I tried this but it did not work:

static wchar_t wbuf[5];
mbtowc(wbuf, buf,5);
return wbuf;

basically I need to do :

wchar_t* x = convert_to_wide_char("my title")
SetWindowTextW(x)


Share this post


Link to post
Share on other sites
Decibit    140
"mbtowc" converts only a single character into unicode format. To covert a sequence of chars use "mbstowcs". Sorry for this mistake. (Their names are so similar.) Use

static wchar_t wbuf[5];
mbstowcs(wbuf, buf,5)
SetWindowTextW(wbuf)

This should work.

Share this post


Link to post
Share on other sites
Genjix    100
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?

Share this post


Link to post
Share on other sites
MaulingMonkey    1728
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]

Share this post


Link to post
Share on other sites
Nitage    1107
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().

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this