String Duplication

78 Views Asked by At

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);

    
}
1

There are 1 best solutions below

0
chqrlie On

is there another solution to modify to string literals...

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:

#include <stdio.h>

int main() {
    char s1[] = " hello ";
    s1[1] = 'b';
    printf("%s\n", s1);
    return 0;
}

Is the solution really valid and optimal?

The code posted is not valid: it does not compile and it is not optimal as you compute the string length twice: once in strlen and another time in strcpy.

Also note that strdup is a reserved name for a POSIX standard function that is semantically equivalent to your function and this strdup() function will finally be included in the C Standard in its upcoming version known as C23.

Finally s2 should be freed after use for good style.

Here is a corrected version.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *my_strdup(const char *src) {
    size_t size = strlen(src) + 1;
    char *dst = malloc(size);
    if (dst == NULL)
        return NULL;
    else
        return memcpy(dst, src, size);
}

int main(void) {
    const char *s1= " hello ";
    char *s2 = my_strdup(s1);
    if (s2) {
        s2[1] = 'b';
        printf("%s\n", s2);
        free(s2);
    ]
    return 0;
}