简体   繁体   中英

Strdup() and strcpy

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

(error) Allocation with strdup, 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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