Created
October 21, 2021 22:19
-
-
Save CGuichard/f50a2dc7febcc166b33d2db7acf44dba to your computer and use it in GitHub Desktop.
Implementation of the strdup function in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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