[ C語言生活記事 ] - String 相關的 function (6) strdup

簡單實現C語言中有幾個string相關的function。

part 6 - strdup (string duplicated)

Function Name : strdup

Definition : This function is going to duplicate the input string to another allocated space.

Prototype : char *strdup_imp ( char *str );

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

char *strdup_imp ( char *src )
{
    char *dest = (char *)malloc( strlen(src) + 1 );
    if( dest == NULL )
        return NULL;

    strcpy(dest , src);
    return dest;
}

int main()
{
    char s1[30] = "stringA";
    char *ret_ptr = strdup(s1);
    
    printf("result = %s\naddr of s1 = 0x%x\naddr 0f return ptr = 0x%x\n", ret_ptr, s1, ret_ptr);

    return 0;
}

 

Result : 

sh-4.2$ gcc -o main *.c 
sh-4.2$ main
result = stringA
addr of s1 = 0x26e527a0 
addr 0f return ptr = 0x602010