这个功能可以更安全吗?寻找提示和您的想法!

标签 c unsafe

这个问题有点奇怪。

我写了一个 C 函数。它“像”strchr/strrchr。它应该在 C 字符串中寻找一个字符,但向后查找,并返回指向它的指针。由于 c 字符串不是“null initiated”,它还需要第三个参数“count”,指示它应该向后查找的字符数。

/*
*s: Position from where to start looking for the desired character.
*c: Character to look for.
*count: Amount of tests to be done
*
* Returns NULL if c is not in (s-count,s)
* Returns a pointer to the occurrence of c in s.
*/
char* b_strchr(const char* s,int c,size_t count){

    while (count-->0){

        if (*s==c) return s;
        s--;
     }
     return NULL;
}

我已经对其进行了一些测试,但是 你看到它有什么缺陷吗?安全问题还是什么?有什么改进吗?可以改进吗? 更重要的是:这是个坏主意吗?

一些用法。

    char* string = "1234567890";

    printf("c: %c\n",*b_strchr(string+9,'5',10));//prints 5

    printf("c: %c\n",*b_strchr(string+6,'1',7));//prints 1

编辑:新界面,一些变化。

/*
* from:  Pointer to character where to start going back.
* begin: Pointer to characther where search will end.
*
* Returns NULL if c is not between [begin,from]
* Otherwise, returns pointer to c.
*/
char* b_strchr(const char* begin,int c,const char* from){


    while (begin<=from){

        if (*from==c) return from;
        from--;
     }
     return NULL;
}

最佳答案

经过编辑更好,但界面仍然令人惊讶。我将 begin 参数(正在搜索的 haystack)作为第一个参数,c 参数 (正在搜索的 needle)第二,from 参数(搜索的起始位置)第三。在相当大的一组 API 中,该顺序似乎是惯用的。

关于这个功能可以更安全吗?寻找提示和您的想法!,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1077479/

相关文章:

xml - 以安全的 Rust 方式切片 XML 字符串

c# - 快速迭代多维字符串数组

c - 指向结构数组的指针

c - 数组将数字列表中的相同数字存储两次

arrays - 在稳定 Rust 中,如何将最小值移出数组,删除其他值?

c# - 如何将 int 设置为 byte* C#

c# - 为什么不能在 C# 7.2 的结构中同时使用只读缓冲区和固定大小缓冲区

c++ - 标称情况优先与正 boolean 表达式

c - libnfc 模拟标签类型4(14443b)

c - 在c中水平翻转BMP图像