I have few issues regarding when to use malloc or in this case strdup.
Below is the small function which I have stolen from internet.
I am trying to understand the code but stuck with few issues.
1. the code has assigned value to psrc and pdest. example
char* psrc = dups;
char* pdest = s;
Doubt: don’t we need to use malloc to allocate space for psrc and pdest.? If not then why.
pdest [0] = '\0';
The above line allocates termination character at the starting ofpdeststring. then previously why we have assignedpdesttos. examplechar* pdest = s;?
Any help or criticism will be helpful to me.
Thanks and regards,
Sam
char* deldupchars (char* s)
{
char* dups = strdup (s);
if (dups)
{
char* psrc = dups;
char* pdest = s;
char ch;
pdest [0] = '\0';
while ((ch = *psrc++) != '\0')
{
if (! strchr (pdest, ch))
{
*pdest++ = ch;
}
}
pdest [0] = '\0';
free (dups);
}
return s;
}
No need to allocate here since
dupswas allocated bystrdup.No need to allocate here since
swas allocated by the caller.This writes into the contents of the string. The assignment
pdest = sassigns pointers but not contents.