In July 22, I went to the interview for a development position. The interviewer first asked me what programs I had written in the previous project, and I spoke about a bunch of code written by balabara, mainly test tools and automated test code. Then let me write the memcpy function. The interviewer is quite good. help me write all the function prototypes. below is my code.
Void memcpy (void * DEST, void * SRC, int Len)
{
Void * P = DEST;
Void * q = SRC;
If (DEST = NULL | src = NULL)
{
Return;
}
For (INT I = 0; I <Len; I ++)
{
* P ++ = * q ++;
}
}
After the interview, I felt good about myself, but later HR told me that it was not acceptable. I did not expect a colleague from the company to talk about similar functions the next day, I know how serious my mistakes are.
1. The function prototype should be void * memcpy (void * DEST, const void * SRC, size_t count). Although the prototype that the interviewer wrote to me is incorrect, but I should check it out earlier.
2. According to the ANSI (American National Standards Institute) standard, you cannot perform algorithm operations on the void pointer, that is, you cannot perform operations on the void pointer, such as P ++, therefore, you need to convert it to a specific type pointer, for example, char *.
3. memcpy operates on the memory and may encounter memory overlaps. The same problem exists in memmove, but the two functions in the source code are processed differently:
The regions in DEST and source in memcpy cannot overlap. Otherwise, the regions in DEST and source in unknown results cannot overlap. Otherwise, unknown results may appear. Function not done
For any memory processing, whether the memory overlaps is controlled by the programmer.
In memmove, memory overlaps are determined. When the memory overlaps, copy from the back to ensure that the replication process is normal.
The source code is as follows:
Void * _ cdecl memcpy (
Void * DST,
Const void * SRC,
Size_t count
)
{
Void * ret = DST;
# If defined (_ m_ia64)
{
_ Declspec (dllimport)
Void rtlcopymemory (void *, const void *, size_t count );
Rtlcopymemory (DST, SRC, count );
}
# Else/* defined (_ m_ia64 )*/
/*
* Copy from lower addresses to higher addresses
*/
While (count --){
* (Char *) DST = * (char *) SRC;
DST = (char *) DST + 1;
Src = (char *) SRC + 1;
}
# Endif/* defined (_ m_ia64 )*/
Return (RET );
}