Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ program crashes

I've this assignment to implement strcmp function. Sometimes it runs okay but other times it crashes. Please help me.

#include <iostream>

using namespace std;     

int mystrcmp(const char *s1, const char *s2);

int main()
{
cout<<mystrcmp("A","A")<<endl;     
cout<<mystrcmp("B","A")<<endl;     
cout<<mystrcmp("A","B")<<endl;     
cout<<mystrcmp("AB","A")<<endl;

return 0;     
}

int mystrcmp(const char *s1, const char *s2)
{
 while (*s1==*s2)
 {
  s1++;
  s2++;
 }

 if(*s1=='\0')
  return(0);

 return(*s1-*s2);
}
like image 700
John Avatar asked Dec 09 '25 22:12

John


2 Answers

It will crash if both the input are identical, because your loop continues beyond the terminating nul character.

To fix this you must have a check for nul character inside the loop as:

while (*s1==*s2) {

  // if s1 points to nul character, then s2 should also, because of the ==
  // which means we've reached the end of the strings and they are equal
  // so return 0.
  if(*s1=='\0')
    return 0;

  s1++;
  s2++;
 }

 return *s1-*s2;
like image 131
codaddict Avatar answered Dec 12 '25 12:12

codaddict


Your mystrcmp will happily run off the end of the string, because your test for the NUL terminator is outside the loop. If the strings are the same, then both *s1 and *s2 are 0 and the loop keeps going.

like image 44
Ben Voigt Avatar answered Dec 12 '25 10:12

Ben Voigt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!