How to return a string-literal from a std::string?
I have a requirement to manipulate a const char* and to return a new const
char*.
i.e If user gives " someThing ", the function should trim the spaces and
return "someThing".
const char* foo (" someThing ") {
// some logic ..;
return "someThing";
}
The following works, but valgrind barfs stating "Invalid Read of size 1".
size_t trim (char*& str)
{
char *c = str;
// empty-string, no input given.
if (!str)
{
return 0;
}
// remove all leading whitespaces
while (isspace(*c))
{
c++;
}
str = c;
c = str + strlen(str) - 1;
// remove the trailing spaces
while (isspace(*c))
{
c--;
}
*(c+1) = '\0';
return strlen(str);
}
const char* foo (const char* str)
{
// copying to char* ... to modify
char *copy = new char[strlen(str) + 1];
strncpy (copy, str, strlen(str));
copy [strlen(str)] = '\0';
// modify ... remove the spaces
trim(copy);
// Intend to return "copy" as String-Literal
// How to make sure that copy is stored as string-literal ?
std::string ret (copy);
// Avoid memory-leaks
delete [] copy;
copy = 0;
// Am i really returning string-literal ??
// or
// Will it be an invalid Pointer
return ret.c_str();
}
// Usage is like
class Bar {
public :
Bar (const char* str) : expr (foo(str)) {
// EMPTY BODY
}
private :
std::string expr;
};
string.c_str() returns a pointer to the std::string internal buffer. For
different user-inputs, i wanted foo() to create string-literals.
When i debug, found out that the memory for return string is allocated on
HEAP. Donno whether this behaviour is platform (RHEL 5.4) or compiler
specific (gcc 4.1.2).
Since the return-string (from foo()) will be out-of-scope once the
function call is over, the valgrind-log "INVALID READ OF SIZE 1" seems to
be reasonable.
Q1) Is the (above) method proper to achieve the objective ? (objective :
modify user-input if required and return string-literal)
Q2) How to make sure that string/string.c_str() returns a string-literal ?
Q3) Is there any other effective way to do the same ?
No comments:
Post a Comment