How is the string printing characters of the previous testcase even after declaring it again in the while loop of testcase?

Viewed 33
    #include <bits/stdc++.h>
#include <stdio.h>
using namespace std;

void Fun(char *s) {

    for(int i=0;s[i]!='\0';i++){
        while(s[i]!='\0' && s[i]!='.' ){
           cout<<s[i];
           i++;
      }
      cout<<" ";
    }

}

int main() {
    int t;
    cin >> t;
    while (t--) {
        char s[10000];
        cin >> s;
        Fun(s);
        cout<<endl;    
    }
}

Input :

2
i.like.this.program.very.much
pqr.mno

Output :

i like this program very much 
pqr mno his program very much 

Why are the characters of my previous string being printed in the next test case even though I've declared the character array again in the while loop ? If I simply print the string using for loop, it prints the right answer, but not this way. I do not get the reason why this is happening?

2 Answers

After s[i] becomes '\0' in the inner loop and exiting the inner loop, i++ in the outer loop is executed and it will see beyond the region where the string is read.

In the first case, though the contents is indeterminate because it is not initialized, it happened to become zeros and stopped printing. In the second case, the contents is also indeterminate, but input in previous case happened to remain and it was printed.

To avoid this, you should break the loop when you see the null-character.

void Fun(char *s) {

    for(int i=0;s[i]!='\0';i++){
        while(s[i]!='\0' && s[i]!='.' ){
           cout<<s[i];
           i++;
      }
      cout<<" ";
      if (s[i] == '\0') break; // add this
    }

}

Another solution is to initialize s to prevent previous input from remaining.

int main() {
    int t;
    cin >> t;
    while (t--) {
        char s[10000] = ""; // add = ""
        cin >> s;
        Fun(s);
        cout<<endl;    
    }
}

The for loop is going to break when it receives a null character. But the null character it is supposed to receive is handled in the while loop. the while loop checks, gets a null character, breaks the loop, then a ' ' is printed, i is incremented and the for loop never gets a chance to get the null character.

But even if the for loop doesn't get the null and break, why whould it still print characters from the previous case? Well, in memory where the array is going to place is totally up to the system. In this case, even if you are declaring the array again and again, the array is getting memory in the same place. So, what you are getting is garbage values that were actually part of the previous case.

You may also ask why does the previous values stay even after destroying the array and reconstructing it in the same place? Well, there are no way to wipe out data from this memory. If you consider making all the bits 0, then that too would be some data. So, there is no point of doing it. The best way to handle it would be just to leave and forget about it.

Related