c - if 条件下使用关系运算符的段错误

标签 c if-statement segmentation-fault operator-keyword relational

第一个 if 条件导致段错误。我无法真正理解为什么,因为我在其他地方使用类似的 if 子句和关系运算符。感谢您提前提供的帮助。

int foo(char *str1,char **str2, char **str3)
{
  char *token1;
  char *token2;
  char *token = strtok(str1, "\"");
  int spaces = strcmp(token,"  ");
  int parenthesis = strcmp("{",token);
  if((token == NULL) || ((spaces != 0) && (parenthesis != 0))) 
  {
    printf("ERR.\n");
    return 0;
  } 
  token = strtok(NULL, "\"");
  if(token == NULL)
  {  
    printf("2ERR\n");
    return 0;
  }
  token1= strtok(NULL, "\"");
  if(token1 == NULL || strcmp(token1," -> ") != 0)
  {
    printf("3ERR\n");
    return 0;
  }
  token2 = strtok(NULL, "\"");
  return 1;
  }

最佳答案

如果不使用char[]strtok将会崩溃。您可以使用 strcpy 来绕过它。

char str[80];
strcpy(str, str1);
char *token = strtok(str, "\"");

我不确定您要做什么,但您的代码将在小更改后运行而不会崩溃。

#include <stdio.h>
#include <string.h>
int foo(char *str1,char **str2, char **str3)
{
    char *token1;
    char *token2;

    char str[80];
    strcpy(str, str1);
    char *token = strtok(str, "\"");
    int spaces = strcmp(token,"  ");
    int parenthesis = strcmp("{",token);
    if((token == NULL) || ((spaces != 0) && (parenthesis != 0)))
    {
        printf("ERR.\n");
        return 0;
    }
    token = strtok(NULL, "\"");
    if(token == NULL)
    {
        printf("2ERR\n");
        return 0;
    }
    token1= strtok(NULL, "\"");
    if(token1 == NULL || strcmp(token1," -> ") != 0)
    {
        printf("3ERR\n");
        return 0;
    }
    token2 = strtok(NULL, "\"");
    return 1;
}
int main() {

    char * c1, * c2, * c3;
    c1 = "foobaz";
    c2 = "bar";
    c3 = "baz";

    int i =  foo(c1, &c2, &c3);
    return 0;
}

关于c - if 条件下使用关系运算符的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41361042/

相关文章:

c - 为什么在使用 snprintf 时会出现此代码的段错误?

c - 使用 mmap 将文件读取为字符串

c - 编译 gcc-5.2.0 时出现问题

c - 删除数组中间的元素?

c - recv 返回旧数据

c - 字符串文字的 strcat 与 strncat

c - 条件宏中的转到标签技巧

node.js - 在 libpthread.so 中运行 Node 时出现段错误

javascript - 更改可变文本颜色

jquery 如果单击元素,则执行此操作,否则执行此操作