-3

I have written this code to find number of occurrences of a word in a line.

It worked fine on my Cygwin terminal. But now when I run it on my Linux machine it is crashing at 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 Two Three Four One Two One Four","Three") << endl;
    system("PAUSE");
return 0;
}

EDIT: Edited the title . This is common to both C and C++

Gaurav K
  • 2,864
  • 9
  • 39
  • 68
  • 1
    `cout <<` not in `C`. – Jayesh Bhoi Aug 19 '14 at 06:03
  • 1
    This is not C, this is C++. – cha5on Aug 19 '14 at 06:05
  • @cha5on Please refer function findWord(char* line,char* word) This is 'c' . I just tried to run it on visual studio c++ – Gaurav K Aug 19 '14 at 06:07
  • I'm aware those are C functions, but you're just calling C functions from C++. Yes, it's pedantic. – cha5on Aug 19 '14 at 06:10
  • @GauravK: Yes, the problem with your program seems to be one that is common to both C and C++, but in general, be careful with the differences between C and C++. Sometimes there are subtle (and not so subtle) differences between these two languages, and exactly the same code may or may not work the same. Especially when having a problem that you don't know the cause of, I would recommend to be a bit pedantic with which language you are using. – Thomas Padron-McCarthy Aug 19 '14 at 06:12
  • Since you are compiling it as C++ code, didn't you get `warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]`? If not, I suggest you up your warning level, `-Wall -Wextra` is reasonable with *gcc*. Oh, and then do fix the warnings you get, of course :) – hyde Aug 19 '14 at 06:25

2 Answers2

3

Your pointer line points to (the first character in) the constant string "One Two Three Four One Two One Four". You try to overwrite this string, which is undefined behaviour since a C implementation should be allowed to put it in read-only memory. Anything can happen. In Cygwin it happened to work as you expected, and in Linux it crashed.

Thomas Padron-McCarthy
  • 27,232
  • 8
  • 51
  • 75
0

char* line

it's pointer and pointed it at a constant string. The compiler puts that in a part of memory that is marked as read-only.Modifying it cause Undefined behaviour.

Community
  • 1
  • 1
Jayesh Bhoi
  • 24,694
  • 15
  • 58
  • 73