Is the malloc'd string automatically freed when string str goes out of scope |
No.
do I still have to call:
free( str.c_str() );? |
This is also incorrect. You did not malloc str.c_str -- so you shouldn't free it. You malloc'd converted_result, so that's the buffer you'd need to free.
Since you are passing converted_result directly to str's constructor, you have no opportunity to free it and are therefore leaking memory.
To prevent the leak you'd need to do something like this:
1 2 3 4 5
|
char* tempbuf = convert_str( p_unconverted_str->c_str(), p_unconverted_str->length() );
string str( tempbuf );
free( tempbuf ); // free it now that we're done with it
( *p_map )[ str ] = str.length();
|
Note that 'str' doesnt' use tempbuf internally. It
copies it into its own internal buffer. So we can free tempbuf immediately after we give it to str.
str will free its own copy, so we don't need to worry about cleaning up str. But it will not clean up tempbuf.
Would it be better to use
auto_ptr< char > |
No. auto_ptr only works when you use singular new (ie: not new[], not malloc), so you can't use it in this case.
Really, it's better to just use strings and not bother with char pointers at all.
Does vector use the copy constructor of string to create its own copy |
Yes.
You don't have to worry about what vector and string do. They clean up after themselves. You should only worry about cleaning up things you allocate yourself.
if I use free( str.c_str() ); |
Again -- you must
NEVER do this.
As I previously mentioned, it's best if you just avoid char arrays completely. They just make things complicated. The best way to do this would be like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
string convert_str( const string& type_a )
{
string converted_result;
// perform conversion
return converted_result;
}
void test( map< string, int >* p_map, string* p_unconverted_str )
{
string str( convert_str( *p_unconverted_str ) );
( *p_map )[ str ] = str.length();
}
|
Let string take care of the memory management. That way you dont' have to worry about anything.
Also, malloc has no place in C++.