gpt4 book ai didi

c - 将 ptrdiff_t 的正值分配给 size_t 是否安全

转载 作者:行者123 更新时间:2023-12-01 12:11:19 26 4
gpt4 key购买 nike

我正在尝试实现 strlen函数,我遇到了这个实现
linux kernel :

size_t strlen(const char *s)
{
const char *sc;

for (sc = s; *sc != '\0'; ++sc)
/* nothing */;
return sc - s;
}

根据C标准,操作的最佳拟合类型 sc - s
ptrdiff_t。

现在在这个片段中, sc保证大于或等于 0 , 意思是
我们没有返回否定类型的风险。

对于正值,返回 sc - c 是否安全如 size_t ?换句话说,是否有可能在
现实世界,一个实现具有 PTRDIFF_MAX大于 SIZE_MAX ?

这是我对 strlen 的实现:
size_t strlen(const char *s)
{
size_t size = 0;

while (*s != '\0') {
size++;
s++;
}

return size;
}

最佳答案

是的,如果传递有效对象是安全的,因为 2 个指针的减法只能用指向同一对象的指针来完成。

6.5.6 Additive operators

  1. When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements. ...


sizeof运算符(operator)最多可以返回 SIZE_MAX , 表达式 sc - s永远不会返回比这更大的。

关于c - 将 ptrdiff_t 的正值分配给 size_t 是否安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51671896/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com