C++ segmentation error when first parameter is null in comparison operator overload

Posted by user1774515 on Stack Overflow See other posts from Stack Overflow or by user1774515
Published on 2012-10-25T15:15:00Z Indexed on 2012/10/25 17:00 UTC
Read the original article Hit count: 211

I am writing a class called Word, that handles a c string and overloads the <, >, <=, >= operators.

word.h:

friend bool operator<(const Word &a, const Word &b);

word.cc:

bool operator<(const Word &a, const Word &b) {
  if(a == NULL && b == NULL)
    return false;

  if(a == NULL)
    return true;

  if(b == NULL)
    return false;

  return a.wd < b.wd;  //wd is a valid c string
}

main:

char* temp = NULL;     //EDIT: i was mistaken, temp is a char pointer
Word a("blah");    //a.wd = [b,l,a,h]
cout << (temp<a);

i get a segmentation error before the first line of the operator< method after the last line in the main. I can correct the problem by writing

cout << (a>temp);

where the operator> is similarly defined and i get no errors. but my assignment requires (temp < a) to work so this is where i ask for help.

EDIT: i made a mistake the first time and i said temp was of type Word, but it is actually of type char*. so i assume that the compiler converts temp to a Word using one of my constructors. i dont know which one it would use and why this would work since the first parameter is not Word.

here is the constructor i think is being used to make the Word using temp:

Word::Word(char* c, char* delimeters=NULL) {
  char *temporary = "\0";
  if(c == NULL)
    c = temporary;
  check(stoppers!=NULL, "(Word(char*,char*))NULL pointer");  //exits the program if the expression is false
  if(strlen(c) == 0)
    size = DEFAULT_SIZE;  //10
  else
    size = strlen(c) + 1 + DEFAULT_SIZE;
  wd = new char[size];
  check(wd!=NULL, "Word(char*,char*))heap overflow");
  delimiters = new char[strlen(stoppers) + 1];      //EDIT: changed to []
  check(delimiters!=NULL,"Word(char*,char*))heap overflow");
  strcpy(wd,c);
  strcpy(delimiters,stoppers);
  count = strlen(wd);
}

wd is of type char*

thanks for looking at this big question and trying to help. let me know if you need more code to look at

© Stack Overflow or respective owner

Related posts about c++

Related posts about parameters