Weird program behaviour

In the code below, how is the value of string b changing? Check in the output. The string b should contain value "you what?" for the input I give, but its value changes suddenly in between.

I have not given the main code I was trying to implement because the problem lies here.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*Program to find no. of Substrings of a type*/

#include<iostream>
#include<string.h>
#include<fstream>        /*using fstream to post the output here*/
using namespace std;

int main()
{
    char a[100];
    int i=0,j=0;
    
    cin.getline(a,100);/*the input string*/
    char s2[]="you"; /*the substring*/
    
    char *b=strstr(a,s2);
    
    ofstream fout;
    fout.open("file.txt");
    
    fout<<b<<endl<<endl;
    
    
     
     while(b[j]!='\0')
                      {
                       fout<<b<<endl;
                       fout<<a<<endl<<endl;    
                       a[j]=b[j];
                                          
                       fout<<"Change\n"<<a[j]<<" "<<b[j]<<"\n\n";  /*Why and how is string 'b' chnging?*/
                       
                       j++;
                       
                       }
                       
     /*Hidden the actual code I was trying to implement because the problem is above*/                  
    return 0;
}


INPUT: hey you what?
you what?

you what?
hey you what?

Change
y y

you what?
yey you what?

Change
o o

you what?
yoy you what?

Change
u u

you what?
you you what?

Change
   

you what?
you you what?

Change
w w

wou what?
you wou what?

Change
h h

whu what?
you whu what?

Change
a a

wha what?
you wha what?

Change
t t

whatwhat?
you whatwhat?

Change
? ?

Last edited on
Because b pointing to the same memory area a is pointing, so all changes to a reflected on b

1
2
3
4
5
a −−−−\
      V
      hey you what?\0
          ^
b −−−−−−−−/
Last edited on
Oh!! that really makes a lot of sense. How should I rectify that?
1
2
char b[100]
strncpy(b, strstr(a,s2), 99);
Last edited on
So, is it true that if I have two strings which overlap by chance, C++ allocates them the same memory location for the part in which they are same?
C++ allocates them
No, strstr() function returns a pointer to the first encountered substring in a. And then you assign it to b, so it points inside a now.
Morale: do not use c-strings in c++ if you does not know exatcly what are they and how do they behave.
Last edited on
Thanks a lot. I get it now. :)
Topic archived. No new replies allowed.