0

C++ strcpy

As strcpy is dangerous due to over run,we tend to use strncpy I read somewhere that it is also dangerous as it does not append null char at end in case of overrun. Is this true? Refer code and observe that calculated length is 5 as it is size we set while allocating. Now, if it exactly stores 5 char, where does null get stored? Or if it's not so, does it only allow us to copy N-1 through strncpy? https://code.sololearn.com/cu7wU4LeJR2A

1st Apr 2021, 4:30 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
2 Answers
+ 1
In your example strncpy indeed only copied 5 chars. It just so happens that there is a null character after that allocated buffer hence the length of the string is being reported as 5.
1st Apr 2021, 6:18 PM
Anthony Maina
Anthony Maina - avatar