Strings in C are null-terminated.
The C programming language has a set of functions implementing
operations on strings (character strings and byte strings) in its
standard library. Various operations, such as copying, concatenation,
tokenization and searching are supported. For character strings, the
standard library uses the convention that strings are null-terminated:
a string of n characters is represented as an array of n + 1 elements,
the last of which is a "NUL" character.
In this case, you should have enough memory to store the original string contents and the "NUL" character (length+1). And don't forget to ensure the presence of the "NUL" character after the end of the string.
There are many possible ways to implement char * copyStr(char[])
function:
1) Your way (corrected):
char * copyStr(char s[])
{
int i;
size_t len = strlen( s );
char * p = (char*) malloc( len + 1 );
for( i = 0; i < len; i++ )
p[i] = s[i];
p[i] = '\0';
return p;
}
2) Using memcpy()
:
char * copyStr(char s[])
{
size_t len = strlen( s );
char * p = (char*) malloc( len + 1 );
memcpy( p, s, len );
p[ len ] = '\0';
return p;
}
3) Using strcpy()
:
char * copyStr(char s[])
{
size_t len = strlen( s );
char * p = (char*) malloc( len + 1 );
strcpy( p, s );
return p;
}
4) Using strdup()
:
char * copyStr(char s[])
{
return strdup(s);
}
Note: For every malloc()
function call you need a free()
function call, your main()
needs a little modification for correctness:
int main( int argc, char ** argv )
{
char * str;
char * res;
str = "music is my aeroplane";
res = copyStr( str );
printf( "The copied string is : %s", res );
free(res); /* freedom */
getch();
return 0;
}
Hope it Helps!