开发者

Strdup() and strcpy

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

(error) Allocation with str开发者_如何学JAVAdup, strcpy doesn't release it

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. The pointer to the memory that is passed to strcpy is never saved anywhere and the compiler can therefore prove that it is leaked.

I'm not sure what you are trying to do since strdup performs both allocation and copying, the call to strcpy seems superfluous.


strdup doing something similar to this (Taken from paxdiablo's answer here) :-

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 .


The problem is strdup calls malloc() inside and passes the resulting pointer to your code. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜