September 26, 2020

strcpy function from string.h implementation in C

In this blog post, I am writing my own implementation in C for the strcpy function.

You can watch the youtube video to see the live implementation of it.

In this implementation, I return a new string rather than copying the value into the memory block pointed at by the pointer provided by the user.

Because, in the case where user passes a string which is present in the read only memory block of the program. Then the program will crash with segmentation fault.

I allocate a memory block big enough to hold destination string.

I copy the destination string in the new string memory block.

Then I copy the source string into the new string memory block, and this new copy starts from the 0th index.

And, I replace the NULL byte copied by the source string with the char value present at the same position in destination string.

You can read the entire source code over here -> StrCpy GitHub.

char * strcpy(char * restrict destinationString, char * restrict sourceString){
    if(NULL == destinationString || NULL == sourceString) return NULL;
    int const destinationStringLength = strlen(destinationString);
    int const sourceStringLength      = strlen(sourceString);

    if(destinationStringLength < sourceStringLength) return NULL;
    char * newString = (char *) malloc(sizeof(char) * (destinationStringLength + 1));
    char * charIterator = newString;
    //copy the destination string
    while((*charIterator++ = *destinationString++) != '\0');

    charIterator = newString;
    //copy the source string
    while((*charIterator++ = *sourceString++) != '\0');
    //remove null value put by source string
    if(destinationStringLength > sourceStringLength) newString[sourceStringLength] = destinationString[sourceStringLength];

    return newString;


Tagged on: