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);
}
memcpy()instead ofstrcpy()because you already know the length (or would if you captured the return value ofstrlen()in a variable)