zoukankan      html  css  js  c++  java
  • strdup函数的使用方法

    函数名: 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 thenew string is obtained with

    malloc(3), and can be freed with free(3).

    The strndup() function is similar, but onlycopies at most n charac-

    ters. If s is longer than n, only ncharacters are copied, and a termi-

    nating NUL is added.

     

    strdup函数原型:

    strdup()主要是拷贝字符串s的一个副本,由函数返回值返回,这个副本有自己的内存空间,和s不相干。strdup函数复制一个字符串,使用完后要记得删除在函数中动态申请的内存,strdup函数的參数不能为NULL,一旦为NULL,就会报段错误,由于该函数包含了strlen函数,而该函数參数不能是NULL。

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

    }

     

    实例1:

    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 ", dup_str);free(dup_str); return 0;

    }

     

    实例2:

    #include <stdio.h>

    #include <stdlib.h>

    #include <string.h>

    unsigned int Test()

    {

    charbuf[]="Hello,World!";

    char* pb =strndup(buf,strlen(buf));

    return (unsignedint)(pb);

    }

     

    int main()

    {

    unsigned int pch= Test();

    printf("Testing:%s ",(char*)pch);

    free((void*)pch);

    return 0;

    }

    在Test函数里使用strndup而出了Test函数仍能够操作这段内存,而且能够释放。

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

    解决方法眼下本人仅仅想到两个: 一个外部变量,如传递一个内存块指针给函数,但这样的做法就是你得传递足够的内存,也就是你不能事先知道这个函数究竟要多大的BUFFER。

     还有一种方法就是在函数内部申请static变量,当然这也是全局区的变量,但这样的做法的缺点就是,当函数多次执行时,static变量里面的数据会被覆盖。这样的类型的还有一个方法就是使用全局变量,但这和使用static变量非常同样,不同的是全局变量能够操作控制,而static变量假设不把它传出函数,就不可对它操作控制了。还有一类方法就是上面所述的,利用堆里的内存来实现,但存在危急。strdup是从堆中分配空间的!strdup调用了malloc,所以它须要释放!对于堆栈:堆是由程序猿来管理的,比方说new,malloc等等都是在堆上分配的!

    栈是由编译器来管理的。

  • 相关阅读:
    【windows】ping对方ip端口,tcping工具
    【mysql】搜索带字符
    【layui】日期选择一闪而过问题
    【转】【linux】查看文件夹大小
    【bat】睡眠2秒
    【mysql】'XXX.XXX.XXX' isn't in GROUP BY问题解决
    【java】获取客户端访问的公网ip和归属地
    【bat】判断字符串是否包含某字符串
    【bat】【windows】win10查看所有wifi密码
    【idea】【sonarlint】指定文件夹扫描
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/3855978.html
Copyright © 2011-2022 走看看