strdup(): Duplicating string

#include <stdio.h>
#include <string.h>
int main()
{
    char str1[] = "plus2net";
    char *str2;
    str2 = strdup(str1);

    printf("Duplicated string : %s", str2);
    return 0;
}
The output of above code is here
Duplicated string : plus2net
We can duplicate a string by using strdup() string function.
duplicate_string = strdup(main_string);
Output is pointer of duplicate_string.

Example: Custom Implementation of strdup()

A custom function that duplicates strings for environments where strdup() isn't available.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char* custom_strdup(const char* str) {
    char* dup_str = malloc(strlen(str) + 1);  // Allocate memory
    if (dup_str != NULL) {
        strcpy(dup_str, str);  // Copy string content
    }
    return dup_str;
}

int main() {
    char original[] = "Plus2Net";
    char* copy = custom_strdup(original);

    if (copy != NULL) {
        printf("Original: %s\n", original);
        printf("Copy: %s\n", copy);
        free(copy);  // Free allocated memory
    } else {
        printf("Memory allocation failed!\n");
    }
    return 0;
}
Output
Original: Plus2Net
Copy: Plus2Net

Example: Using strdup() with Arrays of Strings

Shows how strdup() can be useful when working with arrays of strings, ensuring dynamic memory allocation.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    const char* names[] = {"Alice", "Bob", "Charlie"};
    char* name_copies[3];

    for (int i = 0; i < 3; i++) {
        name_copies[i] = strdup(names[i]);
        if (name_copies[i] != NULL) {
            printf("Copied name: %s\n", name_copies[i]);
            free(name_copies[i]);  // Free the duplicated string
        } else {
            printf("Memory allocation failed for %s\n", names[i]);
        }
    }

    return 0;
}
Output
Copied name: Alice
Copied name: Bob
Copied name: Charlie


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com






    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer