Skip to content

Instantly share code, notes, and snippets.

@CGuichard
Created October 21, 2021 22:19
Show Gist options
  • Save CGuichard/f50a2dc7febcc166b33d2db7acf44dba to your computer and use it in GitHub Desktop.
Save CGuichard/f50a2dc7febcc166b33d2db7acf44dba to your computer and use it in GitHub Desktop.
Implementation of the strdup function in C
/**
* @file strdup.c
* @author CGuichard
* @standard C99
* @version 1.0
* @date 22th October 2021
*
* @brief Implementation of the strdup function in C
*
* This file implements the function strdup in C. As the name implies,
* it duplicates strings.
*
* First, it allocates a new pointer of the size of the old string plus one,
* because we need to end our new string with '\0'. After that,
* we simply copy the data from the old pointer to the new one with memcpy.
*
* Don't forget to free the new string!
*/
#include <string.h>
#include <stdlib.h>
char* strdup(const char* srcString) {
size_t len = strlen(srcString) + 1;
char* newString = (char *) malloc(len * sizeof(char));
if (newString == NULL) {
return NULL;
}
return (char *) memcpy(newString, srcString, len);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment