strcpy
String copy or strcpy is a library function. We are discussing how this function works. It takes two buffers- first one the the destination buffer where string should be copied. This can be an uninitialized buffer. Source buffer is the second argument. This should be a NULL terminated string. Strcpy has no way to validate destination buffer length thus programmer should provide a buffer which is at least the size of source string (destination buffer size >= source string). If destination buffer is smaller than source then strcpy can corrupt data or heap segment depending on the location of destination buffer.
strcpy - pictorial view
strcpy implementation code
strlen
String length or strlen is a library function. It takes a string buffer and this should also be a NULL terminated string. We iterate till the NULL character is reached. There a variable to note down the length and it is initialized to zero. Each character iteration we are doing in the loop, we are incrementing the length value by one. Thus this will give us the length when NULL is reached. This logic is again used in the strcat function to reach at the end of the string.
strlen implementation code
strcat
String Concatenation or strcat is again a library function. It also take two buffer, first one the the destination buffer where string should be combined. This should be a null terminated string. Source buffer is the second argument. This should also be a NULL terminated string. Strcat has no way to validate destination buffer length thus programmer should provide a buffer which is at least the combined size of source string and destination string (destination buffer size >= source string + destination string). If destination buffer is smaller than it can corrupt data or heap segment depending on the location of destination buffer.
strcat - pictorial view
strcat implementation code
Note: Length of a buffer is calculated by (string length + 1). One extra character is for taking NULL termination into consideration. While allocating memory correct allocation should be malloc(strlen(src)+1);.
About our authors: Team EQA
You have viewed 1 page out of 252. Your C learning is 0.00% complete. Login to check your learning progress.
Further readings
memmove vs memcpy how different? implement your own code?
memmove vs memcpy, memmove and memcpy difference understanding overlapping memory with diagram. Implement your own memmove memcpy. example source code
How strrev() works? Explain working principle with source code.
Explain implementation details of strrev. Explain working principle of strrev with source code. Shows how to swap characters with diagram
How to duplicate a string? (String duplication with strdup)
How to duplicate a string? (String duplication with strdup)
How to split/tokenize a string? (strtok() string tokenizer)
How to split/tokenize a string? (strtok() string tokenizer)