欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

[已解决] ‘strncpy‘ output truncated before terminating nul copying?bytes from a string of the same leng

发布时间:2024/3/12 编程问答 46 豆豆
生活随笔 收集整理的这篇文章主要介绍了 [已解决] ‘strncpy‘ output truncated before terminating nul copying?bytes from a string of the same leng 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

1. 解决方法

下面这样写会出错,因为作为函数的参数时,数组名会降级为指针,使用sizeof得到的结果将会始终为4(一个char指针的大小)。

char* dest_str; char* src_str = "source char string"; strncpy(dest_str, src_str, sizeof(src_str));

正确应为:

dest_str= (char*)malloc(strlen(src_str) + 1); // 注意给'/0'留位置 strcpy(dest_str, src_str);

或者是

dest_str= strdup(src_str);

不过注意strdup不是c库标准函数,linux中不包括。所以如果需考虑移植性,使用第一种好点。

2. 参考资料

https://www.huwoo.net/2019/post-3168.html

https://stackoverflow.com/questions/13553113/char-array-split-ip-with-strtok

https://stackoverflow.com/questions/27587090/how-to-get-rid-of-call-is-the-same-expression-as-the-source-warning-in-c

https://www.jb51.net/article/71501.htm

总结

以上是生活随笔为你收集整理的[已解决] ‘strncpy‘ output truncated before terminating nul copying?bytes from a string of the same leng的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。