Reputation: 347
I wanted to transfer elements from a string to another string, and hence wrote the following program. Initially, I thought that the for loop should execute till the NULL character (including it i.e) has been copied. But in this code, the for loop terminates if a NULL character has been found (i.e, not yet copied), but its still able to display the string in which the elements have been copied. How is this possible, if there is no NULL character in the first place?
#include<stdio.h>
#include<stdlib.h>
int main()
{
char temp[100], str[100];
fgets(str, 100, stdin);
int i;
for(i = 0; str[i]!='\0'; i++)
{
temp[i] = str[i];
}
puts(temp);
return 0;
}
Upvotes: 8
Views: 2126
Reputation: 16107
Here is the input and output on my computer:
0
0
絯忐`
Process returned 0 (0x0) execution time : 1.863 s
Press any key to continue.
See the garbage "絯忐`"? This is undefined behavior. Your program works well because you're (un)lucky.
Again, undefined behaviors don't deserve much discussion.
Upvotes: 7
Reputation: 4775
The void puts(const char *)
function relies on size_t strlen(const char *)
and output of this function is undefined when there is no null terminator in the passed argument (see this answer). So in your case the strlen
inside puts
probably found a 0 value 'next to' your array in memory resulting in a proper behavior of puts
, however that need not always be the case as it's undefined.
Upvotes: 7
Reputation: 5850
When you declare char temp[100]
without initialising it to anything, it just takes uninitialised memory. This memory can be anything. For example, the following program will write out the initial contents of that, as integers:
#include<stdio.h>
#include<stdlib.h>
int main()
{
char temp[100];
int i;
for(i = 0; i < 100 ; i++)
{
fprintf(stdout, "%d ", temp[i]);
}
return 0;
}
This prints consistently different output for me, though by some fluke it keeps printing sections of zeros. e.g.:
88 -70 43 81 -1 127 0 0 88 -70 43 81 -1 127 0 0 1 0 0 0 0 0 0 0 112 -70 43 81 -1 127 0 0 0 64 -108 14 1 0 0 0 72 50 -13 110 -1 127 0 0 -128 -70 43 81 -1 127 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 96 -70 43 81
88 90 72 88 -1 127 0 0 88 90 72 88 -1 127 0 0 1 0 0 0 0 0 0 0 112 90 72 88 -1 127 0 0 0 -96 119 7 1 0 0 0 72 18 72 105 -1 127 0 0 -128 90 72 88 -1 127 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 96 90 72 88
88 -6 -79 87 -1 127 0 0 88 -6 -79 87 -1 127 0 0 1 0 0 0 0 0 0 0 112 -6 -79 87 -1 127 0 0 0 0 14 8 1 0 0 0 72 34 57 104 -1 127 0 0 -128 -6 -79 87 -1 127 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 96 -6 -79 87
What's most likely happening is that your non-null-terminated string is being accidentally null-terminated by virtue of the fact that temp[strlen(str)]
is, by a fluke, \0
.
Upvotes: 3