strdup() and strcpy()

函数名: strdup
功  能: 将串拷贝到新建的位置处
用  法: char *strdup(char *str);

C/C++ code
#include  < stdio.h >
#include  < string .h >
#include  < alloc.h >
int  main( void ) {
 
char  * dup_str,  * string  =  " abcde " ;
dup_str = strdup(string);
printf( " %s\n " , dup_str);
free(dup_str);
return  0 ;
 
}


函数名: strcpy
功  能: 串拷贝
用  法: char *strcpy(char *str1, char *str2);
程序例:

C/C++ code
#include  < stdio.h >
#include  < string .h >
int  main( void ) {
char  string [ 10 ];
char  * str1  =  " abcdefghi " ;
strcpy( string , str1);
printf( " %s\n " ,  string );
return  0 ;

用法:#include <string.h>
 功能:复制字符串s
 
 说明:返回指向被复制的字符串的指针,所需空间由malloc()分配且可以由free()释放。
 

The  strdup()  function allocates memory and copies into it the string addressed by s1, including the terminating null character. It is the user's responsibility to free the allocated storage by calling  free() .


 举例:
 
 
      // strdup.c
      
      #include <syslib.h>
      #include <string.h>
 
      main()
      {
        char *s="this is just f";
        char *d;
        
        d=strdup(s);
        printf("%s",d);
 
        getchar();
        return 0;
      }

strdup()主要是拷贝字符串s的一个副本,由函数返回值返回,这个副本有自己的内存空间,和s不相干。

char *strdup(const char *s)
{
        char *t = NULL;
        if (s && (t = (char*)malloc(strlen(s) + 1)))
        strcpy(t, s);
        return t;
}

 

这个函数在linux的man手册里解释为:
The strdup() function returns a pointer to a new string which is a
duplicate of the string s. Memory for the new string is obtained with
malloc(3), and can be freed with free(3).
The strndup() function is similar, but only copies at most n charac-
ters. If s is longer than n, only n characters are copied, and a termi-
nating NUL is added.


这里有一个问题就是strdup函数返回的字符串指针是由malloc在函数内部分配的,那么谁来释放这个动态内存呢?


程序员?还是系统?呵呵,真得很难回答。个人关点是这种做法尽量避免,函数内申请动态内存,而在函数外让程序员来释放,不过每个人都有每个人的观点,呵呵,下面是一个测试例子(无错误处理机制):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
unsigned int Test()
{


char buf[]="Hello,World!";
char* pb = strndup(buf,strlen(buf));
return (unsigned int)(pb);


}
int main()
{


unsigned int pch = Test();
printf("Testing:%s\n", (char*)pch);
free((void*)pch);
return 0;


}
在Test函数里使用strndup而出了Test函数仍可以操作这段内存,并且可以释放。


由这个问题而延伸出来的问题就是,如何让函数得到的内存数据传出函数但仍可用。


解决方法目前本人只想到两个:

     一个外部变量,如传递一个内存块指针给函数,但这种做法就是你得传递足够的内存,也就是你不能事先知道这个函数到底要多大的BUFFER。

     另一种方法就是在函数内部申请static变量,当然这也是全局区的变量,但这种做法的缺点就是,当函数多次运行时,static变量里面的数据会被覆盖。这种类型的另一个方法就是使用全局变量,但这和使用static变量很相同,不同的是全局变量可以操作控制,而static变量如果不把它传出函数,就不可对它操作控制了。


另一类方法就是上面所述的,利用堆里的内存来实现,但存在危险。

 

strdup是从堆中分配空间的!


strdup调用了malloc,所以它需要释放!


对于堆栈:
堆是由程序员来管理的,比如说new ,malloc等等都是在堆上分配的!
栈是由编译器来管理的。

 

strdup的工作原理:

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

 

Duplicates a string.

Syntax

LPTSTR StrDup(      
    LPCTSTR lpsz );

Parameters

lpsz
A pointer to a constant null-terminated character string.

Return Value

Returns the address of the string that was copied, or NULL if the string cannot be copied.

Remarks

StrDup will allocate storage the size of the original string. If storage allocation is successful, the original string is copied to the duplicate string.

This function uses LocalAlloc to allocate storage space for the copy of the string. The calling application must free this memory by calling the LocalFree function on the pointer returned by the call to StrDup.

Example

This simple console application illustrates the use of StrDup.

  Copy Code
#include <windows.h> #include <shlwapi.h> #include <stdio.h> void main(void) { char buffer[] = "This is the buffer text"; char *newstring; // Note: Never use an unbounded %s format specifier in printf. printf("Original: %s\n", buffer); newstring = StrDup(buffer); if (newstring != NULL) { printf("Copy: %s\n", newstring); LocalFree(newstring); } } OUTPUT: - - - - - - Original: This is the buffer text Copy: This is the buffer text
}

The difference between strcpy() and strdup():

strcpy will not allocate the memory for the copy for you, which means you have to give it not only the pointer to the string to copy, but also a pointer to the place to copy it to, which you have set up yourself. strdup will grab itself a place to copy the string to, which you will have to free up later when you don't need the copy anymore.

函数名: strdup
功  能: 将串拷贝到新建的位置处
用  法: char *strdup(char *str);
程序例:

C/C++ code
#include  < stdio.h >  #include  < string .h >  #include  < alloc.h >  int  main( void ) {  char  * dup_str,  * string =  " abcde " ; dup_str  =  strdup( string ); printf( " %s\n " , dup_str); free(dup_str);  return  0 ; }


函数名: strcpy
功  能: 串拷贝
用  法: char *strcpy(char *str1, char *str2);
程序例:

C/C++ code
#include  < stdio.h >  #include  < string .h >  int  main( void ) {  char  string [ 10 ];  char  * str1  =  " abcdefghi " ; strcpy( string , str1); printf( " %s\n " ,  string );  return  0 ; }

************************************************

strdup不是标准的c函数,所以linux会报错!~
strcpy是标准的c函数,在windows里报错是因为指针没申请空间吧!~
可以先strlen判断from的大小,之后为to申请空间,之后再strcpy就不会报错了!~

*************************************************

 

strdup可以直接把要复制的内容复制给没有初始化的指针,因为它会自动分配空间给目的指针
strcpy的目的指针一定是已经分配内存的指针

*************************************************

你可能感兴趣的:(strdup() and strcpy())