Reputation: 8728
Is the following function safer than using memcpy? Memcpy gives the following "Improper_Null_Termination" Error in Checkmarx static code analysis: The string in at line is stripped of its terminating null-byte by at . However, if I use the following function, Checkmarx has no issue:
void myMemCpy(void *dest, void *src, size_t n)
{
// Typecast src and dest addresses to (char *)
char *csrc = (char *)src;
char *cdest = (char *)dest;
// Copy contents of src[] to dest[]
for (int i=0; i<n; i++)
cdest[i] = csrc[i];
}
Are there any problems with using this function instead of memcpy()?
Upvotes: 1
Views: 918
Reputation: 1
Is the following function safer than using memcpy?
No. It's the same. At best.
If anything, since code analyzers and compilers know what memcpy()
does, this code is less safe.
Especially given the way you pass size_t
and then improperly use an int
loop counter:
void myMemCpy(void *dest, void *src, size_t n)
{
// Typecast src and dest addresses to (char *)
char *csrc = (char *)src;
char *cdest = (char *)dest;
// Copy contents of src[] to dest[]
for (int i=0; i<n; i++)
cdest[i] = csrc[i];
}
On a 64-bit architecture with 32-bit int
and 64-bit size_t
, that's going to fail spectacularly if n
is a value over 2 gig.
Upvotes: 7