Segmentation fault using relational operators in if condidtion

96 views Asked by At

The first if condition leads to a segmentation fault. I can't really comprehend why, since I use similar if clauses with relational operators elsewhere. Thanks for your help in advance.

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;
  }
1

There are 1 answers

2
Niklas Rosencrantz On

The strtok will crash if you don't use char[]. You can get around it using strcpy.

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

I'm not sure what you're trying to do, but your code will run without crashing after the small change.

#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;
}