0

I've implemented a couple of functions to generate random strings,

char *ran_string(int max, int min){  //random string with max length and min length

    int tam=rand()%max,i=0;
    char *str;
    if(tam<min)
        tam=min;
    str=malloc(sizeof(char)*tam);
    for(i=0;i<tam;i++) {
        if(i==0){
            str[0]=(char)((rand() % 26) + 65); //Upercase ascii
        }
        else{
            str[i]=(char)((rand() % 26) + 97);  //Lowercase ascii
        }

    }
    return str;
}

char *var_ran_string(int num, int max, int min){ //generates num random strings
    char *a;
    a=malloc(sizeof(char)*num*max);
    strcat(a,ran_string(max,min));
    for(int i=0;i<num-1;i++){
        strcat(a," ");
        strcat(a,ran_string(max,min));
    }
    return a;
}

I´ve tested it out, and the second time that i call var_ran_string it always prints weird characters like h�1�Dvdfn�2�|��� Zlbhh���. Tried calling the function thousands of times, but the second time seems the only problem.

Sam Mason
  • 15,216
  • 1
  • 41
  • 60
  • 2
    What is the definition of a "string" in C? How does code know how long a string is? – David Schwartz Mar 26 '21 at 00:02
  • 2
    One problem: `strcat(a,ran_string(max,min));`. That's undefined behaviour because `a` does not contain a C string as required by `strcat`. Init `a` contents with `a[0] = '\0';` – kaylum Mar 26 '21 at 00:02
  • 1
    Your `ran_string` function allocates enough memory for `tam` characters but not the necessary null terminator. And it doesn't add a null-terminator either. You're also leaking the memory allocated by `ran_string`. – jarmod Mar 26 '21 at 00:04
  • @kaylum strcat probably accepts it, since i´ve tested it out for an iteration of 1000 and the only line bugged was the second one, but i will change and see the result. – Leonh kapa Mar 26 '21 at 00:06
  • 1
    No that's wrong. This is called Undefined Behaviour in C. It may appear to "work", even 1000s of time. But it will fail at some point if you add more code, run on a different machine, use a different compiler, etc. Why argue with something like this - it is clearly wrong. [Undefined, unspecified and implementation-defined behavior](https://stackoverflow.com/questions/2397984/undefined-unspecified-and-implementation-defined-behavior) – kaylum Mar 26 '21 at 00:11
  • @jarmod You are right, it needed the null-terminator, working as intented now. Thx everybody – Leonh kapa Mar 26 '21 at 00:24
  • You are aware that a disproportionate number of strings generated will have the minimum length, right? e.g. if you have min=100 and max=200, fully half the random lengths generated will be less than min, and will thus be set *to* min. To get a uniform distribution over lengths, you want to do something like `tam = min + (rand() % (max-min))`. (Assuming max is an exclusive upper bound). – Ray Mar 29 '21 at 16:41

0 Answers0