Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

strcpy replaced by a better function

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
Hello

as you know strcpy can be fatal, if dest is not as big as src. In this case an error can occur.

For this I did my own strcpy-function:

//Allocates memory for dest as much as needed
void scopy(char *dest, const char *src)
{
if ( (dest = (char*) malloc( (strlen(src) + 1) * sizeof(char) ) ) != NULL )
strcpy(dest, src);
else
{
fprintf(stderr,"Error while copying string\n",);
exit(1);
}
}

But this permanently causes errors. What's wrong?

Any help is greatly appreciated.

Thanks in advance.

BinLadenKiller
 
hi blk,
what errors do u c?
how about this.. ?

void scopy(char **dest, const char *src)
{
if ( (*dest = (char*) malloc( (strlen(src) + 1) * sizeof(char) ) ) != NULL )
strcpy(*dest, src);
else
{
fprintf(stderr,"Error while copying string\n",);
exit(1);
}
}

in using..
char *mydest, char str[]="hello";
scopy(&mydest, str);
.. use ..
free(mydest); // this bcomes a essential and possible error source for ur application.. each ptr will need to b free'd
secondly u cannot copy char *const ptrs!!

hope that helps,
shail
 
Hello shail,

yeah, ur absolutely right. Now I see the problem.

Thank you very much.

BinLadenKiller
 
I think the error is in the comparision stmt:

(dest = (char*) malloc( (strlen(src) + 1) * sizeof(char) )


what u 're doing is checking the pointer's address of the two pointers,not the length.It seems so.


Magesh
 
Magesh,

The statement with pointers is perfect! The error was somewhere else... the addresses in the pointers played the trick!;-)

Chow!

J Roy
user.gif
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top