A random text as output

64 views Asked by At

My goal is a function that returns the same text as I wrote in stdin. As a result of compilation of the code below:

#include <stdio.h>

char chain[990];
int znaki()
{
scanf("%s", chain);
int i=0;
do{
    putchar(chain[i]);
    i++;
}
while(chain[i]!=10);
return 0;
}
int main(int argc, char **argv)
{
znaki();
return 0;
}

I get:

MyOwnText

MyOwnText

and

many

lines

of some random text just like cat /dev/random in linux

The first line is my input. Why?

3

There are 3 answers

2
Bill Lynch On
  1. You have an array.
  2. You asked the user for a word, and you stored it in the beginning of that array.
  3. You then printed the array.

It's pretty obvious to me why the input you wrote was printed out.

0
Innot Kauker On
do {
    putchar(chain[i]);
    i++;
} while(chain[i]!=10);

This code prints characters from chain (and further) until finds a char with code 10. As the buffer is uninitialized, it is filled with some random data from other programs. And you see that data. Probably, you wanted to write something like

do {
    putchar(chain[i]);
    i++;
} while(i != 10);

which would print first 10 chars from the array.

And by the way, the code seems to be vulnerable to a buffer overflow.

0
chux - Reinstate Monica On

chain[] does not have the value of 10.

chain is filled with non-white-space characters - that is what "%s" directs scanf() to do: scan and save non-white-space char. 10 is typically '\n', a white-space.

char chain[990];
scanf("%s", chain);
...
while(chain[i]!=10);

Instead use fgets() to read lines.

int znaki(void) {
  char chain[990];
  while (fgets(chain, sizeof chain, stdin) != NULL) {
   int i=0;
   while (chain[i] != '\n' && chain[i] != '\0') {
     putchar(chain[i]);
     i++;
   }
   return 0;
 }