简体   繁体   English

Strdup()和strcpy

[英]Strdup() and strcpy

void x( )
{
    strcpy(a, strdup(p) );
}

(error) Allocation with strdup, strcpy doesn't release it (错误)使用strdup进行分配,strcpy不会释放它

Can anyone tell me what's wrong with above statement and why I am getting this error? 谁能告诉我上面的陈述有什么问题以及为什么我会收到这个错误?

The problem is that you are leaking memory. 问题是你正在泄漏记忆。 The call to strdup allocates memory which is not freed. strdup的调用分配了未释放的内存。 The pointer to the memory that is passed to strcpy is never saved anywhere and the compiler can therefore prove that it is leaked. 传递给strcpy的内存指针永远不会保存在任何地方,因此编译器可以证明它已泄露。

I'm not sure what you are trying to do since strdup performs both allocation and copying, the call to strcpy seems superfluous. 我不确定你要做什么,因为strdup执行分配和复制,对strcpy似乎是多余的。

strdup doing something similar to this (Taken from paxdiablo's answer here) :- strdup做类似的事情(取自paxdiablo的回答) : -

char *strdup (const char *s) {
char *d = malloc (strlen (s) + 1);   // Allocate memory
if (d != NULL)
    strcpy (d,s);                    // Copy string 
return d;                            // Return new memory

} }

SO leaking the memory which has been allocated inside strdup leads to that error . 泄漏已经在strdup中分配的内存会导致该错误。

The problem is strdup calls malloc() inside and passes the resulting pointer to your code. 问题是strdup调用malloc()并将结果指针传递给你的代码。 Your code doesn't take ownership of that allocated memory and it is leaked. 您的代码不会获取已分配内存的所有权并且它已被泄露。 You code is roughly doing this: 您的代码大致是这样做的:

char* duplicate = malloc(strlen(p)+1); //first part of strdup
memcpy(dupliate,p); //second part of strdup
memcpy(a, duplicate);//memcpy in your code

the above code doesn't free() memory pointed to by duplicate . 上面的代码没有free() duplicate指向的内存。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM