Ah. Let's look closely at what the function does:
Code:
char* str = (char*) malloc( sizeof(char)* chars+1);
if ( !str ) return 0;
So, memory was (hopefully) allocated, and str points to the first character of that block of memory. Well and good. Later, we see:
Code:
while ( from++ < to )
{
printf("[%c] >> [%c] \n", *begin, *str);
*str++ = *begin++;
}
*str++ = 0 ;
Okay, the values were assigned in a loop, then you took care to null terminate the string. Great!
Unfortunately, at this point str points one past the null character. But it really should point to the start of the copied string!
There are two ways to fix this:
- Create another pointer that is a copy of str before the loop, then return this second pointer.
- Subtract the copied string length (including the null character) from str, thereby getting a pointer to the start of the copied string that is then returned.
Personally I think the first way is less error-prone.
By the way, since src is a const char*, this:
Code:
char* begin = &src[from];
should be:
Code:
const char* begin = &src[from];
EDIT:
Incidentally, you have a problem with one of your debugging outputs:
Code:
printf("[%c] >> [%c] \n", *begin, *str);
*str++ = *begin++;
You print *begin, and begin does indeed point to where you want to copy. However, until the next statement, *str does not yet contain the value that is to be copied, so printing it is wrong.