String copy methods and pitfalls

Below I mainly talk about the three types of memcpy, strcpy, string :: copy

Memory copy memcpy

Trap
Memory copy will not check the string end character '\ 0'

Result After
copying, garbled characters will appear at the end of the string.

Solution When
applying for memory, apply for one more byte of memory to ensure that the end of the string is copied into it.

String copy strcpy

strcpy is a function dedicated to string copying. The difference from memcpy is that it will detect the end character '\ 0', so there is no need to do extra applications when applying for memory.

Syntax / prototype:
char * strcpy (char * strDestination, const char * strSource);

Parameter description:
strDestination: destination string.
strSource: source string.

strcpy () will copy the string pointed to by strSource to strDestination.

You must ensure that strDestination is large enough to accommodate strSource, otherwise it will cause an overflow error.

string method copy string :: copy

Trap & result
Because the function finally called by copy here is still memcopy, so the trap is the same. After the copy is completed, a string of garbled characters will be brought behind the string

Solution
After copying, add the end character '\ 0'.

Published 181 original articles · Like 13 · Visitors 10,000+

Guess you like

Origin blog.csdn.net/qq_43461641/article/details/105075700