无法在 C 中正确使用 strstr()

标签 c string glibc

所以我正在用 C 构建一个 Web 服务器。我想使用正则表达式解析请求,但目前我想我应该先做一些快速的事情来让它工作。目前,我正在实现 cookie 并确定请求是否具有我正在使用的 cookie 字段。

int find_cookie(const char * request){
    char * start_pointer = NULL;
    long ret = 0;

    if ((start_pointer = strstr(request, "Cookie:") != NULL)){
        //Do stuff with the pointer
        //such as using strtol to get the value as a number
        ret = strtol(start_pointer + strlen("Cookie:"), NULL, 10);
    }else return 0;

    return (int) ret;
}

现在,人们会认为问题出在 strtol() 上。但是,在使用 GDB 之后,我注意到当没有 cookie 字段时,它会返回 NULL(如预期的那样),但另一方面,如果它存在并且我尝试打印 start_pointer 的值,它将打印:“无法访问内存地址 0x1”。这是怎么回事?顺便说一句,当我调试程序时,我可以看到请求变量包含整个请求,并且我在末尾添加了一个“\0”。

最佳答案

你的操作顺序错了。试试这个:

if ((start_pointer = strstr(request, "Cookie:")) != NULL){

否则,您会将 start_pointer 设置为比较结果,即 1(真)。

关于无法在 C 中正确使用 strstr(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54893953/

相关文章:

c - 解析制表符分隔的文本文件

c - 在C中将字符串拆分为数组

linux - `GLIBC_2.16' 找不到应用程序

c++ - C 编译器错误 : cdefs. h 未找到

java - 在 Java 中加密和解密文本

c - 如何将 readlink 与动态内存分配一起使用

在 C 中使用 MPI 进行代码并行化

C -printf 类型转换

c++ - C++ 中的 C 字符串删除

java - 使用 int 作为 GregorianCalendar 的输入,但无法继续扫描 JAVA