5

I want to generate a random string text of length 100 with the code below, then to verify that I print the length of the variable text but sometimes that is less than 100. How can I fix that?

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

int main() {
    int i, LEN = 100;
    srandom(time(NULL));
    unsigned char text[LEN];
    memset(text, 1, LEN);
    for (i = 0; i < LEN; i++) {
        text[i] = (unsigned char) rand() & 0xfff;
    }
    printf("plain-text:");
    printf("strlen(text)=%zd\n", strlen(text));

}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Juan
  • 2,073
  • 3
  • 22
  • 37
  • 1
    You may want to read up on ascii if you are not already familiar, there are a lot of ascii codes which are not atypical of a string – Joshua Byer Apr 26 '15 at 23:32
  • 1
    Note: Is not `text[i] = (unsigned char) rand() & 0xfff;` the same as `text[i] = ((unsigned char) rand()) & 0xfff;`? So why the `& 0xfff`? – chux - Reinstate Monica Apr 26 '15 at 23:33
  • 1
    Small points: 1) Unix `srandom()` goes with [`random()`](http://linux.die.net/man/3/srandom) and std C `srand()` works with `rand()`. 2) Consider `size_t LEN` rather than `int`. – chux - Reinstate Monica Apr 26 '15 at 23:45

2 Answers2

5

Perhaps a random character 0 was added to the string, and then it is considered as the end of string by strlen.

You can generate random characters as (rand() % 255) + 1 to avoid zeros.

And at the end you have to zero-terminate the string.

LEN = 101; // 100 + 1
....
for (i = 0; i < LEN - 1; i++) {
    text[i] = (unsigned char) (rand() % 255 + 1);
}
text[LEN-1] = 0;
AlexD
  • 32,156
  • 3
  • 71
  • 65
3

I want to generate a random string text of length 100 with the code below, then to verify that I print the length of the variable text but sometimes that is less than 100. How can I fix that?

  1. First of all, if you want to generate a string of length 100, you'll need to declare an array of size 101.

    int i, LEN = 101;
    srandom(time(NULL));
    unsigned char text[LEN];
    
  2. When you are assigning the characters from the call to rand, make sure that it is not 0, which is usually the null terminator for strings.

    for (i = 0; i < LEN - 1; /* Don't increment i here */) {
        c = (unsigned char) rand() & 0xfff;
        if ( c != '\0' )
        {
           text[i] = c;
    
           // Increment i only for this case.
           ++i
        }
    }
    

    and don't forget to null terminate the string.

    text[LEN-1] = '\0';
    
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
R Sahu
  • 204,454
  • 14
  • 159
  • 270