当strlen的参数为非零结尾的字符串时,其返回值在IF语句中不安全?

问题描述 投票:0回答:1

我被strlen的问题困扰了很久,代码如下

char temp[100] = {0};
memset(&temp , 1, 110);
int len = strlen(temp);

printf ("test strlen of temp %d \n", len);
if (len > 100)
{
        xxxx;
}
else
{
        xxxx;
}

你可以看到,我向strlen传递了一个参数temp,返回值“len”肯定是110。 但 !!!!!接下来的语句 if (len > 100) 为 false!!!!!!!!!!!!!!!!!!!!!!!!!!!

系统:linux CPU架构:32位ARM

请帮助我!!!!,谢谢

我测试过的东西:

  1. 如果你将 len 值赋给另一个 int 变量,事情就会好起来。像下面这样

示例:

char temp[100] = {0};
memset(&temp , 1, 110);
int len = strlen(temp);

int len1 = len;

if (len1 > 100) ? TRUE!
  1. len 的每个字节: 0x6e、0x00、0x00、0x00
c linux strlen
1个回答
1
投票

memset(&temp , 1, 110);
不好,因为它尝试在
temp[]
数组之外写入。这是未定义的行为(UB)。此时或稍后的代码中任何事情都可能发生。

strlen(temp);
也是 UB,因为
strlen()
需要一个指向 string 的指针,而数组
temp
不是 string,因为它缺少 null 字符

不要期望代码在具有 UB 时表现良好。
不要指望代码在具有 UB 时会失败。

相反,消除 UB。

char temp[100] = {0};
//memset(&temp , 1, 110);
memset(&temp , 1, 99);
int len = strlen(temp);
© www.soinside.com 2019 - 2024. All rights reserved.