0
 int main(){    
       char s[1000];    
       s[0]='Q';    
       printf("%d",strlen(s));    
       return 0;    
    }

The above code is giving 6 as output. The output should be 1 in this case.

int main(){    
       char s[1000];     
       printf("%d",strlen(s));    
       return 0;    
}

This code was even giving 6 as output. where it should be 1000 or 0 or some garbage value. I have tried it in " hackerrank ", but it was giving 6 as the length. When the same code was tried in TURBOC it was giving the correct answer. I was unable to find the reason for this output. Can someone please sort it out and give the exact solution to this problem.

MVP
  • 21
  • 2

2 Answers2

3

Local non-static variables, like your array, will not be initialized. Its value or contents will be indeterminate.

That means the likelihood of your array containing a string terminator where you want it to be is close to zero.

Passing your array without initialization to a string-function leads to undefined behavior.

You need to explicitly initialize your array, like e.g.

char s[1000] = "";
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
2

The line:

char s[1000];  

declares an array of 1000 chars but it doesn't put anything in it. Because it is a local variable, it is allocated on the stack and, apart from reserving the necessary space to hold 1000 chars, the compiler doesn't generate any code to set their content (to zero or something else).

All 1000 values are garbage. It just happens that the 7th of them is zero. strlen() stops counting when it reaches it and returns 6 but this value is also garbage. It could be 230790345 or something else as well. It could also produce an infinite loop, a segmentation fault or make you spit fire like a dragon. Anything is possible and permitted by the language in this situation. It is called Undefined Behaviour.

axiac
  • 68,258
  • 9
  • 99
  • 134