-1

I wrote this code -

char s1[10] = "he",  s2[20] = "she", s3[30], s4[30];

printf("%d %d", strlen(s2) + strlen(s3), strlen(s4));

output -

6 9

Then I wrote this code -

char s1[10] = "he",  s2[20] = "she", s3[30], s4[30];

printf("%d %d", strlen(s3), strlen(s4));

by removing strlen(s1) +

output -

0 3

My question in how the length of string s4 changes ?

Akhil Raj
  • 457
  • 1
  • 4
  • 14
  • 2
    `s3` and `s4` are uninitialized, so probably undefined behaviour. – Sizik Dec 22 '15 at 18:22
  • In the first example, `s4` is uninitialized, so `strlen(s4)` can be anything. Indeed, the same goes for `strlen(s3)` since `s3` is uninitialized. It does depend a bit on where the variables are defined. If they're global, they will be initialized, but if they're local to a function, they will not. – Jonathan Leffler Dec 22 '15 at 18:29

2 Answers2

2

s3 and s4 are not initialized and are not '\0' terminated C-strings, which is what strlen() expects. So you can't pass them to strlen().

What you see is undefined behaviour.

P.P
  • 117,907
  • 20
  • 175
  • 238
  • Well I read this in a book, in which it was asked what would be the result of first code ? then I tried to remove ` strlen(s2) +` and I found this ambiguity . – Akhil Raj Dec 22 '15 at 18:27
  • May be, the book had initialized or assigned values to `s3` and `s4` later but before using `strlen()` or had them as global variables? If not, the book is wrong on this. – P.P Dec 22 '15 at 18:30
  • 1
    Consider changing your textbook and use a better one. Here's [SO's list](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list). – P.P Dec 22 '15 at 18:34
2

You say "string s4", but s4 does not contain a string. It's an array of characters with no particular contents. You can only perform a strlen on a C-style string. So your code is just broken. Its behavior will be unpredictable.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • Well I read this in a book, in which it was asked what would be the result of first code ? then I tried to remove ` strlen(s2) +` and I found this ambiguity . – Akhil Raj Dec 22 '15 at 18:27
  • @AkhilRaj The answer is that the code is broken and there's no way to predict the result. With deep understanding of one particular implementation (library, compiler, OS) you may be able to predict what happens on that particular platform, but the C++ specification just says that anything can happen. (I'm guessing that the difference you observed has to do with the change in stack alignment.) – David Schwartz Dec 22 '15 at 18:30