strstr不是indexOf

strstr不是indexOf

strstr是C语言中查找字符子串的函数。

1
char* strstr(const char *pstr, const char* pstrSearch);

indexOf是现代语言中常见的查找子字符串的函数。

1
int indexOf(strSearch);

indexOf返回的是子字符串索引位置,strstr返回的是找到的字串的地址指针。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
char *buf = malloc(256);
//操作buf
...

char * key= "searchKey";

//bug产生的地方
int idx = strstr(buf, key);
if(idx > 0){
buf[idx] = '\0';
}

//显示buf内容
...

上述代码以使用indexOf的方式使用strstr,导致想截断字符串时数组越界。最终导致嵌入式设备电流从7ma骤然增加到40ma。

这里截断出错后,其实字符串的显示和预期不同。但这里造成bug的代码过于简单,反而导致找错了方向,浪费了不少时间。