/*************************************************
函数名: strdup
功 能: 将串拷贝到新建的位置处
用 法: char *strdup(char *str);
这个函数在linux的man手册里解释为:
The strdup() function returns a pointer toa new string which is a
duplicate of the string s. Memory for the new string is obtained with
malloc(), and can be freed with free().The strndup() function is similar,
but onlycopies at most n characters. If s is longer than n,
only n characters are copied, and a terminating NUL is added.
Allocates enough storage via malloc() for a copy of the string, copies the
string into the new memory, and returns a pointer to it.
头文件: <stdlib.h>
strdup()主要是拷贝字符串s的一个副本,由函数返回值返回,
这个副本有自己的内存空间,和s不相干。strdup函数复制一个字符串,
使用完后要记得删除在函数中动态申请的内存,strdup函数的参数不能为NULL,
一旦为NULL,就会报段错误,因为该函数包括了strlen函数,而该函数参数不能是NULL
复制字符串,返回指向被复制字符串的指针。所需空间由malloc()分配,
且可以由free()释放。需要注意的是,在调用完这个函数后,一定要记得释放内存空间。
**************************************************/
char * my_strdup(const char *str)
{
char *p;
if (!str)
return(NULL);
if (p = malloc(my_strlen(str) + 1))
return(my_strcpy(p,str));
return(NULL);
}
char * __strdup (const char *s)
{
size_t len =strlen (s) + 1;
void *new =malloc (len);
if (new == NULL)
return NULL;
return (char *)memcpy (new, s, len);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
unsigned int Test()
{
cha
函数名: strdup
功 能: 将串拷贝到新建的位置处
用 法: char *strdup(char *str);
这个函数在linux的man手册里解释为:
The strdup() function returns a pointer toa new string which is a
duplicate of the string s. Memory for the new string is obtained with
malloc(), and can be freed with free().The strndup() function is similar,
but onlycopies at most n characters. If s is longer than n,
only n characters are copied, and a terminating NUL is added.
Allocates enough storage via malloc() for a copy of the string, copies the
string into the new memory, and returns a pointer to it.
头文件: <stdlib.h>
strdup()主要是拷贝字符串s的一个副本,由函数返回值返回,
这个副本有自己的内存空间,和s不相干。strdup函数复制一个字符串,
使用完后要记得删除在函数中动态申请的内存,strdup函数的参数不能为NULL,
一旦为NULL,就会报段错误,因为该函数包括了strlen函数,而该函数参数不能是NULL
复制字符串,返回指向被复制字符串的指针。所需空间由malloc()分配,
且可以由free()释放。需要注意的是,在调用完这个函数后,一定要记得释放内存空间。
**************************************************/
char * my_strdup(const char *str)
{
char *p;
if (!str)
return(NULL);
if (p = malloc(my_strlen(str) + 1))
return(my_strcpy(p,str));
return(NULL);
}
char * __strdup (const char *s)
{
size_t len =strlen (s) + 1;
void *new =malloc (len);
if (new == NULL)
return NULL;
return (char *)memcpy (new, s, len);
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
unsigned int Test()
{
cha