字符串函数strdup

来源:互联网 发布:秒领棒棒糖软件 编辑:程序博客网 时间:2024/06/05 16:40
************************************************************************/
/* 字符串函数strdup,将串拷贝到新建的位置处 ,返回指向被复制的字符串指针
   所需空间由malloc分配,且可以由free自由释放                         
  
/************************************************************************/

#include<iostream>
#include<malloc.h>
#include<assert.h>
using namespace std;

char *Strdup(const char *strSource)
{
 assert(strSource!=NULL);//断言
 char *address,*temp;
 char *record;
 int len=0;
 record=(char *)strSource;//保存源字符串的地址
 while(*record!='\0')//遍历源字符串,获取其长度
 {
  record++;
  len++;
 }
  temp=(char *)malloc(len+1);//分配len+1空间
     address=temp;//保存地址

   while(*strSource!='\0')//将源字符串赋给temp
 {
  *temp=*strSource; 
  strSource++;
  temp++;
  
 }
     *temp='\0';//末尾置'\0'
 return address;
}

  

int main()
{
     char *dup_str;
  char *string1="abcde";
  dup_str=Strdup(string1);
  cout<<dup_str;
  free(dup_str);//使用完Strdup后要用free释放
  return 0;
}

 

strcpy与strdup的区别:

strdup可以直接把要复制的内容复制给没有初始化的指针,因为它会自动分配空间给目的指针;strdup内部在堆上创建了一个备份,所以即使没有看到malloc也应该在使用完毕后手动释放free

strcpy的目的指针一定是已经分配内存的指针