I have the following code in C now
int length = 50
char *target_str = (char*) malloc(length);
char *source_str = read_string_from_somewhere() // read a string from somewhere
// with length, say 20
memcpy(target_str, source_str, length);
The scenario is that target_str
is initialized with 50 bytes. source_str
is a string of length 20.
If I want to copy the source_str
to target_str
i use memcpy() as above with length 50, which is the size of target_str
. The reason I use length
in memcpy is that, the source_str
can have a max value of length
but is usually less than that (in the above example its 20).
Now, if I want to copy till length of source_str
based on its terminating character ('\0'
), even if memcpy length is more than the index of terminating character, is the above code a right way to do it? or is there an alternative suggestion.
Thanks for any help.