Function parameters are local variables of the function. A function deals with copies of its arguments. So any changes of a parameter within the function do not influence on the original value of the corresponding argument.
So for example this statement in function strcopy
dst = (char*)malloc(len);
does not change the argument dst
defined in main.
char *dst = "";
If you want to write indeed a function named like strcopy
when the function should deal with already allocted arrays. Otherwise the function should be named like for example strdup
if it itself creates a new copy of the source string.
Moreover your function is wrong because it can try to allocate a memory with a negative memory size when the source string is empty and therefore strlen(src)
is equal to 0. And in any case it allocates less memory than it is required.
int len = strlen(src) - 1;
dst = (char*)malloc(len);
The function can be defined the following way
char * strcopy( char *dst, const char *src )
{
char *p = dst;
while ( ( *p++ = *src++ ) );
return dst;
}
and called like
int main( void )
{
char *src = "hello";
char dst[6];
printf( "strcpy:%s\n", strcopy( dst, src ) );
return 0;
}
Take also into account that you may not change string literals in C (and C++). Any attempt vto change a string literal results in undefined behaviour of the program.
Thus you may not declare variable dst
like for example
char *dst = "A string literal";
and call function strcopy
passing dst
as the first argument in the above program.
If you want to create a copy of a source string then the function can be defined the following way
char * strdup( const char *src )
{
char *dst = malloc( ( strlen( src ) + 1 ) * sizeof( char ) );
if ( dst )
{
char *p = dst;
while ( ( *p++ = *src++ ) );
}
return dst;
}
and called like
int main( void )
{
char *src = "hello";
char *dst;
dst = strdup( src ) ;
printf( "strcpy:%s\n", dst );
free( dst );
return 0;
}