I'm new to C. I wrote this so it might be incorrect in more ways than one. And I actually wrote it expecting it to break. So, why does it work?
This reads a line from stdin and prints it back to stdout.
I don't understand how I can create--and more importantly--use a character array of size 0. Is it not a sort of buffer between gets() and printf()? Does it only seem to work because it overflows (and potentially breaks something else)? If not, what is happening?
Here's a transcription:
#include <stdio.h>
void main(void)
{
char input[0];
while(gets(input))
printf("%s\n", input);
}
>>359924
>>359931
"gets" doesn't respect array bounds at all. If you made input size 12 instead of 0, and then entered a string more than 12 characters long, you'd begin to access memory you shouldn't be using. Eventually a segfault should happen during runtime with enough characters, even though the program successfully compiles.
fgets is the safer alternative, and newer versions of C don't allow gets at all.
Your analysis is correct. It only works because your buffer overflows.
It's unlikely to break something else because you don't have any other variables and because of your operating system's modern memory management preventing access to important stuff.
If you want to see interesting stuff, try declaring a few variables after your char input[0], and printing those after your gets.
If you want to have some control over your buffer, you can try fgets(input, sizeof input, stdin)
>>359944
>>359948
>If you want to have some control over your buffer, you can try fgets(input, sizeof input, stdin)
That's what I thought at first too when I searched on my own, but see pic related.
Anyway, thanks for confirming my doubts.
Also, how can I safely read from stdin and print to sdtout without any built-in limit on how long a line it can handle then?
>>359949
No: Literally type `sizeof input`, not 10.
>>359952
You can read 1 character at a time and print when you reach '\n', or you can make the buffer something like a megabyte and hope you never want to input the complete works of shakespear at once.
>>359953
It compiled, but did nothing when I executed it. Nice.
When I set the size of the array to a specific value higher than zero, it still breaks the input lines in chunks of that size.
I could not understand how it was able to do that, but I just realized that it is simply because stdin and stdout are two separate streams. So, even if it stops to print, it can still go back to the right place in stdin afterwards.
I feel stupid. It was so obvious.
That was also why I originally rejected the idea of going character by character, but now I see how it could work.
Thanks, anon.
>>359949
If you remove the \n it won't break up the lines
>>359957
Yeah, the part I didn't understand was how it could print it by parts, more than why it was on many lines, but I get it now.
I also successfully implemented a character by character version a few seconds ago.