1

I am trying to write a program in C that spits out random characters. Following instructions I found here, I wrote this program.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


int main(void) {
   srandom((unsigned) time(NULL));
   printf("Tests various aspects of random\n");
   char misc;
   int num, index;
   printf("Enter number of chars: ");
   scanf("%d", &num);
   printf("\n");

   for (int i = 0; i < num; i++) {
      index = random() % 26;
      misc = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"[index];
      printf("%d:%s\n", index, &misc);
   }
}

However, it doesn't behave as I expect. When entering a small number of characters for it to generate, like 10, it makes the expected output.

My expected output is a set of

rand_int:char

pairs printed to the screen.

Here is an example of normal operation

Tests various aspects of random
Enter number of chars: 
7:H

4:E

23:X

2:C

4:E

17:R

22:W

11:L

9:J

4:E

However, if I input a large value such as 100, it outputs very strange things like:

Tests various aspects of random
Enter number of chars: 
18:Sd
3:Dd
21:Vd
10:Kd
19:Td
19:Td
14:Od
7:Hd
15:Pd
22:Wd
24:Yd
22:Wd
12:Md
[rest omitted for brevity...]

So the question is, why does it behave this way? What might be a better approach to avoid this?

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Raven King
  • 155
  • 1
  • 12

2 Answers2

6

The comments made by Jabberwocky and Federico klez Culloca got it right. I was trying to print the character as a string. This was wrong and did weird things. I needed to use:

printf("%d:%c\n", index, misc);

instead of

printf("%d:%s\n", index, &misc);
Yunnosch
  • 26,130
  • 9
  • 42
  • 54
Raven King
  • 155
  • 1
  • 12
2

All is very simple. The program has undefined behavior. You are using the format string %s that is used to output strings.

printf("%d:%s\n", index, &misc);

However the variable misc is not a character array that contains a string. It is just a single character. So the function printf outputs all characters beyond the variable misc until a zero-terminating character is encountered.

And it seems that the variable num is allocated next to the variable misc. So the printf call outputs also bytes of the variable num that contains the value 100. If to output this value stored in a byte as an ASCII character then you will get the character 'd'.

Here is a demonstrative program.

#include <stdio.h>

int main(void) 
{
    char c = 100;

    putchar( c );
    putchar( '\n' );

    return 0;
}

Its output is

d

Instead of the format %s use the format %c in the printf call. For example

printf("%d:%c\n", index, misc);
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335