Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strdup() and strcpy

Tags:

c++

c

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?

like image 529
lokesh Avatar asked Dec 07 '22 19:12

lokesh


2 Answers

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.

like image 56
David Heffernan Avatar answered Dec 09 '22 09:12

David Heffernan


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 .

like image 42
Sandeep Pathak Avatar answered Dec 09 '22 08:12

Sandeep Pathak