在 Libc 上实现原始 strlcpy 函数
#include <stdio.h>
#include <string.h>
size_t ft_strlcpy(char *dst, const char *src, size_t dstsize)
{
unsigned int i;
unsigned int dst_len;
i = 0;
dst_len = strlen(dst);
if (dstsize > 0)
{
while (src[i] != '\0' && i < dstsize - 1)
{
dst[i] = src[i];
i++;
}
dst[i] = '\0';
}
return (strlen(src));
}
int main(void)
{
char dst[100] = "HelloWorld!";
char dst2[100] = "HelloWorld!";
const char src[11] = "teststring";
int dstsize = -1;
printf("mine : %zu\n", ft_strlcpy(dst, src, dstsize));
printf("%s\n", dst);
printf("string.h : %zu\n", strlcpy(dst2, src, dstsize));
printf("%s\n", dst2);
return (0);
}
这段代码是我自己实现strlcpy的代码。
但我有一个疑问。
当 dstsize 为负数时,我的函数不打印任何错误消息。
但原始的 strlcpy 打印 Tracetrap 错误(可能是 Linux 中的 SIGILL。我使用的是 OS X)
我已经搜索了大部分bsd原始c库github,但它们的工作原理都与我的代码相同。我想知道其中的区别。当 dstsize 为负数时,原始 strlcpy 如何打印错误?
这个问题的要点是“当 dstsize 是像原始函数一样的负数时,如何打印跟踪陷阱错误?(我知道它将转换为 size_t max 数。)”
#include <stdio.h>
#include <string.h>
size_t ft_strlcpy(char *dst, const char *src, size_t dstsize)
{
unsigned int i;
unsigned int dst_len;
i = 0;
dst_len = strlen(dst);
if (dstsize > 0)
{
while (src[i] != '\0' && i < dstsize - 1)
{
dst[i] = src[i];
i++;
}
dst[i] = '\0';
}
return (strlen(src));
}
int main(void)
{
char dst[100] = "HelloWorld!";
char dst2[100] = "HelloWorld!";
const char src[11] = "teststring";
int dstsize = -1;
printf("mine : %zu\n", ft_strlcpy(dst, src, dstsize));
printf("%s\n", dst);
printf("string.h : %zu\n", strlcpy(dst2, src, dstsize));
printf("%s\n", dst2);
return (0);
}
This code is my code of implementing strlcpy on my own.
but I have one doubt question.
when dstsize is negative number, my fucntion don't print any error message.
but original strlcpy print Tracetrap error(maybe SIGILL in linux. I'm using OS X)
I have searched most of bsd original c library github, but all of them work same as my code. I want to know the difference. how original strlcpy print error when dstsize is negative number?
This question's point is "how to print trace trap error when dstsize is negative number like original function?(I know it will be converted to size_t max number.)"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没有理由为
strlcpy
计算dst
中字符串的长度:dst_len = strlen(dst);
是无用且适得其反的。这是修改后的版本:
关于您的问题:
如果调用者传递的目标大小是负数,即:使用有符号算术产生或将产生负数的某些计算的结果,它被转换为
size_t
模SIZE_MAX + 1
,因此该值为巨大的。您可以通过比较来检测这一点:
There is no reason to compute the length of the string in
dst
forstrlcpy
:dst_len = strlen(dst);
is useless and counterproductive.Here is a modified version:
Regarding your question:
If the destination size passed by the caller is a negative number, ie: the result of some computation that produces or would produce a negative number using signed arithmetics, it is converted to
size_t
moduloSIZE_MAX + 1
, hence the value is huge.You can detect this by comparison: