-1

Now in this program I tried to concatenate two strings but when I don't provide null character to it's end it produces a unknown value at the end. Now I know the importance of null character but I would to know what happened here to produce the random value at the end of concatenated string and what it is?

First code: With null character inserted

void main(){
    char str1[10],str2[10],output_str[20];  
    int i=0,j=0,k=0;  
    printf("Insert first string: ");
    gets(str1);
    printf("Insert second string: ");
    gets(str2);  

    while(str1[i] != '\0')
        output_str[k++]=str1[i++];
    while(str2[j] != '\0')
        output_str[k++]=str2[j++];

    /*This the line which matters*/
    output_str[k]='\0';

    puts(output_str);
}

Input: First string: Bhushan
Second string: Mendhe

Output: BhushanMendhe

But for the same above code with the same inputs, if I just remove 'The line which matters.' in the code.

Output is: BhushanMendhe0♥↕@

I want to understand why that bolded part in second output was produced when we didn't specify null character and what is it called?

  • 1
    Are you sure you do not have typos here `while(str1 != '\0')` and here `while(str2 != '\0')`? – alk Feb 25 '18 at 09:02
  • I think what you mean in the conditions of the loops is : `while(str1[i] != '\0')` and `while(str2[j] != '\0')` – KarenAni Feb 25 '18 at 09:09
  • The observed behaviour is independent form concatenation. Try this `#include int main(void) { char s1[4] = "abcd"; char s2[5] = "efgh"; puts(s1); }` – alk Feb 25 '18 at 09:09
  • 2
    `♥↕@` I guess that means it loves you... – David C. Rankin Feb 25 '18 at 09:17
  • @alk yes i meant exactly what you said and i have edited it. Thank you! – Bhushan Mendhe Feb 25 '18 at 09:29
  • "Now I know the importance of null character" -- are you sure? The `puts()` function expects a pointer to the first character of a _string_, which is defined as a null-terminated character array in C. That is to say, the `\0` itself is _part_ of the string; without a null-terminator, a character array is not a string at all. Also, [never use `gets()` in real code](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used). – ad absurdum Feb 25 '18 at 14:38

1 Answers1

2

puts() reads the given memory address until it encounters an \0, if you did not specify an \0 it just continues to read the memory (which is some random garbage, probably from the last program). After a certain amount of memory it encounters an \0 and stops reading. If you did not put a \0 at the end you are in danger of running into a segmentation fault.

DZDomi
  • 1,685
  • 15
  • 13