为什么我们需要的strdup()? [英] Why do we need strdup()?

查看:209
本文介绍了为什么我们需要的strdup()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我工作的一个任务,我才知道,我们不应该使用分配,例如:

While I was working on an assignment, I came to know that we should not use assignments such as :

 char *s="HELLO WORLD";

使用这样的语法项目是走向崩溃的倾向。

Programs using such syntaxes are prone towards crashing.

我试过并用:

 int fun(char *temp)
 {
    // do sum operation on temp
    // print temp.
  }
  fun("HELLO WORLD");

即使上述作品(虽然输出为编译器和标准的具体)。

Even the above works(though the output is compiler and standard specific).

相反,我们应该努力的strdup()或使用为const char *

Instead we should try strdup() or use const char *

我曾尝试阅读博客上的其他类似的问题,但无法得到的概念,为什么上面code不应该工作。

I have tried reading other similar questions on the blog, but could not get the concept that WHY THE ABOVE CODE SHOULDNT WORK.

时的内存分配?又请问有什么区别常量化妆??

Is memory allocated?? And what difference does const make??

推荐答案

让我们澄清事情有点。你永远不要特别需要的strdup 。它只是分配的char * 堆的副本的功能。这是可以做到很多不同的方式,包括使用基于堆栈的缓冲区。你需要的是结果,一个的char *的可变副本

Lets clarify things a bit. You don't ever specifically need strdup. It is just a function that allocates a copy of a char* on the heap. It can be done many different ways including with stack based buffers. What you need is the result, a mutable copy of a char*.

原因您列出了code是危险的是,它的传递什么是真正的字符串常量从字符串成需要一个可变的字符串一个插槽。这是不幸的是允许C标准,但ihnherently危险。写一个常量字符串会产生意想不到的结果,并经常死机。在的strdup 函数的修复的,因为它创建它放入插槽期待一个可变的字符串一个可变副本的问题。

The reason the code you've listed is dangerous is that it's passing what is really a constant string in the from of a string literal into a slot which expects a mutable string. This is unfortunately allowed in the C standard but is ihnherently dangerous. Writing to a constant string will produce unexpected results and often crashes. The strdup function fixes the problem because it creates a mutable copy which is placed into a slot expecting a mutable string.

这篇关于为什么我们需要的strdup()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆