c strncpy null terminated or not [duplicate]

百般思念 提交于 2019-12-06 11:03:43
SpacedMonkey

It's talking about the case when strlen(source) > num. It will only copy num chars, none of which is a NUL and it will not add a NUL.

strncpy(dst, src, len) only adds a null terminator to dst if there is a null terminator in src within the first len bytes. Your code might seem to work, because there might or might not be a null character after the array to[]. A better test is:

char source[] = "source";
char dest[] = "destination";
strncpy(dest, source, 6);
printf("%s\n", dest);

The result should be:

sourceation

If you write strncpy(dest, source, 7) instead, then the output is just the word source.

The semantics of strncpy(), even when precisely explained as they are in the C++ reference above, are widely misunderstood. The behavior of this function is counterintuitive and error prone.

To avoid problems when using it or further down the development process, when the maintainer will misread the code and add more subtile bugs, there is a simple solution: NEVER EVER USE THIS FUNCTION.

You can read further details about this in this article by Bruce Dawson.

To answer your question: if the source string is longer than the size passed as a third argument (usually corresponding to the size of the destination buffer), the function will copy size characters to the destination and no null byte will be present among these. Calling strlen(destination); will then invoke undefined behavior because it will attempt to read beyond the end of the array until it finds a null terminator. This specific behavior is what makes strncpy so error prone.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!