I'm implementing a strdup function as an exercise.
char* strdupPtr(const char* str) {
const size_t sz{strlen(str)+1};
char *save, *temp;
save = temp = (char*)malloc(sz);
while((*temp++ = *str++)); // compiler warning with only 1 set of parenthesis
return save;
}
After a few failures I found out that it works properly when the "save"(wiki reference) pointer is returned but not when "temp" is returned. Why do I need to return save instead of temp directly when dealing with pointers(a subscript array version works without the use of save)?
Within the function pointer temp
is incremented.
while((*temp++ = *str++));
So if to return temp
then it will not contain the start address of the allocated memory.
For example these use cases will be invalid.
char *p = strdup( "Hello World" );
puts( p );
free( p );
Take into account that in C++ it is better to use operator new. For example
char * strdupPtr( const char *s )
{
char *p = new char[std::strlen( s ) + 1];
std::strcpy( p, s );
return p;
}
Or you could even write
char * strdupPtr( const char *s )
{
char *p = new char[std::strlen( s ) + 1];
return std::strcpy( p, s );
}