I wonder, is there another solution to modify to string literals and Is the solution really valid and optimal?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *strdup(const char *src) {
char *dst = malloc(strlen (src) + 1);
Space for length plus nul
if (dst == NULL) return NULL;
No memory
strcpy(dst, src); // Copy the characters
return dst; // Return the new string
}
int main( void )
{
const char* s1= " hello "; // A constant character pointer pointing to the string " serhat".
char* s2= strdup(s1);
s2[1]= 'b';
printf("%s", s2);
}
The code does not modify a string literal, it merely modifies an allocated copy. You could use a simpler approach with an initialized array of
char:The code posted is not valid: it does not compile and it is not optimal as you compute the string length twice: once in
strlenand another time instrcpy.Also note that
strdupis a reserved name for a POSIX standard function that is semantically equivalent to your function and thisstrdup()function will finally be included in the C Standard in its upcoming version known as C23.Finally
s2should be freed after use for good style.Here is a corrected version.