Generating a random unsigned char string in C

I want to generate a random text of a line of length 100 with the code below and then check that I am printing the text length of a variable, but sometimes it is less than 100. How can I fix this?

#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));

}

      

+3


source to share


2 answers


Perhaps a random character has been added to the string 0

and then considered the end of the string strlen

.

You can generate random characters like (rand() % 255) + 1

to avoid zeros.



And at the end you need to zero out the null string.

LEN = 101; // 100 + 1
....
for (i = 0; i < LEN - 1; i++) {
    text[i] = (unsigned char) (rand() % 255 + 1);
}
text[LEN-1] = 0;

      

+4


source


I want to generate a random text of a line of length 100 with the code below and then check that I am printing the text length of a variable, but sometimes it is less than 100. How can I fix this?



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

    int i, LEN = 101;
    srandom(time(NULL));
    unsigned char text[LEN];
    
          

  • When you assign characters from a call rand

    , make sure 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 zero out the string.

    text[LEN-1] = '\0';
    
          

+2


source







All Articles