c语言strdup函数

In this article, we’ll take a look at using the strdup() function in C/C++.

在本文中,我们将研究在C / C ++中使用strdup()函数。

The strdup() function is very useful if you want to duplicate the contents of a string onto another string.

如果要将一个字符串的内容复制到另一个字符串上,strdup()函数将非常有用。

Let’s see how we can utilize this function, using some simple examples.

通过一些简单的示例,让我们看看如何利用此功能。



C / C ++中strdup()函数的基本语法 (Basic Syntax of the strdup() function in C/C++)

This takes in an input char* string, and duplicates it into another char* string. It returns the pointer to this string.

这将接受一个输入的char*字符串,并将其复制到另一个char*字符串中。 它返回指向该字符串的指针。

This is also defined inside the header file <string.h>, so we must include it first.

这也是在头文件<string.h>定义的,因此我们必须首先包含它。

Therefore, the function prototype is as follows:

因此,函数原型如下:


#include <string.h>
char* strdup(const char* src);

Since we will not be modifying the input string, we pass it as const char*!

由于我们不会修改输入字符串,因此将其作为const char*传递。

NOTE: This function is NOT defined in the ISO C99 standards, but it is defined in POSIX systems. If you’re unsure about using this function, refer to the below section for a sample implementation.

注意 :此功能未在ISO C99标准中定义,但已在POSIX系统中定义。 如果不确定使用此功能,请参考以下部分的示例实现。

Let’s now look at a simple example, which shows this function coming into play.

现在让我们看一个简单的示例,该示例说明了该功能的作用。



使用strdup()–一个简单的例子 (Using strdup() – A simple Example)

We’ll take an input string, and copy it into another string.

我们将输入一个字符串,并将其复制到另一个字符串中。


#include <stdio.h>
#include <string.h>int main() {char inp[] = "Hello from JournalDev!";char* output = strdup(inp);printf("Input: %s\n", inp);printf("Output: %s\n", output);return 0;
}

Output

输出量


Input: Hello from JournalDev!
Output: Hello from JournalDev!

As you can see, we do indeed get our output to be the same string as the input.

如您所见,我们确实的确将输出与输入的字符串相同。



使用strdup()与使用strcpy() (Using strdup() vs Using strcpy())

You may very well wonder – if strdup() duplicates an input string, and strcpy() copies from an input string, what is the difference?

您可能会很好奇–如果strdup()复制输入字符串,而strcpy()从输入字符串复制,有什么区别?

The difference between the two lies in how these two functions are implemented.

两者之间的区别在于这两个功能的实现方式。

When you use strcpy(dst, src), you are literally copying from the source string to the destination string. Here, you are responsible for both allocating and de-allocating the memory with dst.

使用strcpy(dst, src) ,实际上是从源字符串复制到目标字符串。 在这里,您负责使用dst分配和取消分配内存。

This is because strcpy simply copies data. Here is an elegant one-line implementation from this StackOverflow answer!

这是因为strcpy只是复制数据。 这是此 StackOverflow答案中的一种优雅的单行实现!


void strcpy(char* dst, char* src) {while (*dst++ = *src++);
}

What does this imply? This means that you can use strcpy() on both static (associated with stack) memory as well as dynamic (associated with heap) memory.

这意味着什么? 这意味着您可以在静态(与堆栈相关联)内存以及动态(与堆相关联)内存上使用strcpy()


#include <stdio.h>
#include <string.h>int main() {char a[] = "Hello";// Memory associated with stackchar b[100];strcpy(b, a);// Memory associated with heapchar* c = (char*) malloc (10 * sizeof(char));strcpy(b, c);printf("a = %s\nb=%s\nc=%s\n", a, b);free(c);return 0;
}

Output

输出量


a = Hello
b = Hello
c = Hello

Indeed, we could copy to both static as well as dynamic memory locations, using strcpy().

确实,我们可以使用strcpy()复制到静态和动态内存位置。

Now, strdup() uses malloc() under the hood to automatically allocate the memory for you. However, this means that you must free the memory yourself, after you finish using it!

现在, strdup()strdup()使用malloc()为您自动分配内存。 但是,这意味着您必须在使用完内存后自己释放内存!

So, simply put, strdup() allocates memory using malloc(), and then copies your source string to the allocated memory.

因此,简单地说, strdup()使用malloc() strdup()分配内存,然后将源字符串复制到分配的内存中。

strdup()的示例实现 (A Sample Implementation of strdup())

Here is an efficient implementation, using memcpy() to speed things up, as compared to naive copying using strcpy().

与使用strcpy()进行天真复制相比,这是一种高效的实现,使用memcpy()可以加快处理速度。


char* my_strdup(char* input) {// We need strlen(src) + 1, since we have to account for '\0'int len = strlen(input) + 1;char* output = (char*) malloc ((len + 1) * sizeof(char));if (output == NULL) return NULL;output = (char*) memcpy(output, input, len);return output;
}

Now, let’s look at a complete program, to verify that we can use this properly. Remember, we must also free the memory returned by malloc()!

现在,让我们看一个完整的程序,以验证我们可以正确使用它。 记住,我们还必须释放malloc()返回的malloc()


#include <stdio.h>
#include <stdlib.h>
#include <string.h>char* my_strdup(char* input) {// We need strlen(src) + 1, since we have to account for '\0'int len = strlen(input) + 1;char* output = (char*) malloc ((len + 1) * sizeof(char));if (output == NULL) return NULL;output = (char*) memcpy(output, input, len);return output;
}int main() {char inp[] = "Hello from JournalDev!";char* output = my_strdup(inp);printf("Input: %s\n", inp);printf("Output: %s\n", output);// Free the memory address returned using malloc()free(output);return 0;
}

Output

输出量


Input: Hello from JournalDev!
Output: Hello from JournalDev!

Indeed, we did get the same output as before! And we don’t seem to have any memory leaks, since we freed the corresponding memory at the end.

确实,我们确实获得了与以前相同的输出! 而且我们似乎没有任何内存泄漏,因为我们在最后释放了相应的内存。



结论 (Conclusion)

We learned about we could use the strdup() function in C/C++. We also learned about the differences between strdup() and strcpy(), so use them wisely!

我们了解到可以在C / C ++中使用strdup()函数。 我们还了解了strdup()和strcpy()之间的区别,因此请明智地使用它们!

For similar content, do check out our tutorial section on C programming!

对于类似的内容,请查看我们有关C编程的教程部分 !

参考资料 (References)

  • cppreference.com page on strdup()关于strdup()的cppreference.com页面
  • StackOverflow Question on strcpy() vs strdup()关于strcpy()vs strdup()的StackOverflow问题


翻译自: https://www.journaldev.com/40458/strdup-c-plus-plus

c语言strdup函数

c语言strdup函数_在C / C ++中使用strdup()函数的指南相关推荐

  1. matlab中floor函数,floor函数_怎么在excel中使用floor函数

    floor函数即上取整函数,是计算机C语言中的数学函数,与ceil函数相对应.但是它在excel中却是另一种含义,FLOOR函数是向下舍入为最接近指数基数的倍数,下面小编就教你怎么在excel中使用f ...

  2. python中add函数_如何使用python中的add函数?

    之前向大家介绍过python中的求和函数sum函数,numpy中的sum函数,对于数组可以指定维度进行相加.numpy中还有另一种求和运算方法,即add函数.add函数不仅作用于numpy中加法运算, ...

  3. python中index函数_详解python中的index函数用法

    1.函数的创建 def fun(): #定义 print('hellow') #函数的执行代码 retrun 1 #返回值 fun() #执行函数 2.函数的参数 普通参数 :要按照顺序输入参数 de ...

  4. 原生js已载入就执行函数_手写CommonJS 中的 require函数

    前言 来自于圣松大佬的文章<手写CommonJS 中的 require函数> 什么是 CommonJS ? node.js 的应用采用的commonjs模块规范. 每一个文件就是一个模块, ...

  5. mounted钩子函数_怎样实现Vue中mounted钩子函数获取节点高度

    这次给大家带来怎样实现Vue中mounted钩子函数获取节点高度,实现Vue中mounted钩子函数获取节点高度的注意事项有哪些,下面就是实战案例,一起来看一下. 遇到的问题 最近在开发一个Vue的项 ...

  6. python grid函数_详解numpy中的meshgrid函数用法

    numpy中的meshgrid函数的使用 numpy官方文档meshgrid函数帮助文档https://docs.scipy.org/doc/numpy/reference/generated/num ...

  7. python hasattr函数_浅谈python中的getattr函数 hasattr函数

    hasattr(object, name) 作用:判断对象object是否包含名为name的特性(hasattr是通过调用getattr(ojbect, name)是否抛出异常来实现的). 示例: & ...

  8. python numpy sum函数_如何使用Python中的sum函数?

    之前小编向大家介绍过python中的sum函数(https://www.py.cn/jishu/jichu/22025.html).在python中sunm函数使用分为两种情况,一种是python自带 ...

  9. python中从小到大排序的函数_深入理解Python中的排序函数

    由于 Python2 和 Python3 中的排序函数略有区别,本文以Python3为主. Python 中的排序函数有 sort , sorted 等,这些适用于哪些排序,具体怎么用,今天就来说一说 ...

最新文章

  1. firefox html5 canvas,html5 Canvas
  2. 独家 | 在数据科学中需要多少数学技能?(附链接)
  3. java弧线_数据可视化API之弧线图实现
  4. 【数理知识】《随机过程》方兆本老师-第1章-引论
  5. C语言宏定义、宏替换
  6. spark2.0.1 安装配置
  7. 背景位置 background-position 0916
  8. Oracle数据库备份dmp文件,使用cmd命令导入导出步骤,以及忘记Oracle密码
  9. 系统架构师考试经验分享
  10. 淘宝帝国是如何创建的连载04
  11. react native 获取验证码
  12. 完美解决电脑老是弹出广告窗口!
  13. 计算机一直黑屏,win7系统显示器黑屏但电脑一直在运行如何解决
  14. 车辆身份特征识别引擎
  15. linux 查看内存 udimm rdimm,关于内存类型UDIMM、RDIMM、LRDIMM
  16. 目标检测中的Anchor
  17. 业务数据激增,4张图看清zData如何助力金融企业快速响应IT需求
  18. java宝典app,总结到位
  19. 哈工大软件构造自我复习总结Part1
  20. 美团面试常见问题总结

热门文章

  1. 解密碧生源:消费者买的到底是茶,还是被收购了智商税?
  2. K8S 配置 storageclass 使用 nfs 动态申领本地磁盘空间
  3. 三种Linux的清屏命令方法
  4. Gtest入门介绍(一)
  5. 马踏棋盘问题的程序c语言,请各位C语言大神解释下马踏棋盘的程序,各模块功能,原理,方法,如? 爱问知识人...
  6. 超声波清洗机振子换能器设计
  7. 120KHZ 高频率超声波换能器振子
  8. 构建安装ARM Ubuntu系统
  9. android uid.system,android.uid.system
  10. 经典K线形态组合普及大全!(好文珍藏)