c++ - Occurrence of a word in a line -


i have written code find number of occurrences of word in line.

it worked fine on cygwin terminal. when run on linux machine crashing @ strcpy(line, strstr(line,word))

why such behaviour?

#include <iostream> #include <cstdio> #include <cstring>  using namespace std;  int findword(char* line,char* word) {     int count=0;      int wordlen = strlen(word);      while(true)     {      if( strstr(line,word) == null)      break;       strcpy(line, strstr(line,word)); //crashes here      printf("@@%s\n",line);      strcpy(line,line+wordlen+1);      printf("##%s\n",line);      count++;      } printf("%d\n",count); return count; }  int main() {     cout <<   findword("one 2 3 4 1 2 1 four","three") << endl;     system("pause"); return 0; } 

edit: edited title . common both c , c++

your pointer line points (the first character in) constant string "one 2 3 4 1 2 1 four". try overwrite string, undefined behaviour since c implementation should allowed put in read-only memory. can happen. in cygwin happened work expected, , in linux crashed.


Comments

Popular posts from this blog

java - How to specify maven bin in eclipse maven plugin? -

single sign on - Logging into Plone site with credentials passed through HTTP -

php - Why does AJAX not process login form? -