[已解决] ‘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

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值