Computer Scientist

Monday, 16 April 2012

BE CAUTIONS: when you are using 'strncpy'

In my experiment results, an random error happened quite frequently. But it is not show itself in each time's experiment. It makes me be really frustrated as it is shown in a experiment. The PROBLEM is: an additional extra number always suffix the real number. Due to it happened randomly, which means that no patterns can be found from the situations it is shown, it is difficult to spot the problem's root cause.

What can I do at this point is to skim through the code where it probably happened from. Because this code is written with pure C instead of C++, the most possible reason should be the wrong memory pointer.

After the searching of man docs of the Linux, the reason is found --- the using of 'strncpy'.

When we copy a group of characters to a destination C-type string, a null-termination will be added to the destination automatically as 'strcpy' (without the 'n') is used. There are no problems at all.

However, the 'strncpy' is used, we need to think about the null-termination problem. As the statement of warning in the man doc, if the first 'n' characters of source C-type string have not null-termination in it. This function will not append the '\0' termination to the end of destination string automatically. This is not related to the size of destination string. We only need to be bare in mind the size of n and the first n characters of source string.

SOLUTION: add the '\0' termination to the destination string manually.