Search code examples
carraysstringc-stringssrand

Random character strange defined behavior


I'm using an array in this code because i need a string which should be always modified, that's why i'm not using a pointer, howewer everytime i run the code i get a strange behavior at the 31th iteration.

code

int i = 0;
char name[100];
srand(getpid());


while(i<100) {

    name[i] += (char)'A'+(rand()%26);
    printf("%d strlen\n", i+1);
    printf("%s\n", name);
    printf("/////\n");
    i++;    
}

output

/////
30 strlen
IKXVKZOLKHLTKBFFTUZCYXHYVEBZOY
/////
31 strlen
IKXVKZOLKHLTKBFFTUZCYXHYVEBZOYJ
/////
32 strlen
IKXVKZOLKHLTKBFFTUZCYXHYVEBZOYJWttime
/////
33 strlen
IKXVKZOLKHLTKBFFTUZCYXHYVEBZOYJW�time
/////
34 strlen
IKXVKZOLKHLTKBFFTUZCYXHYVEBZOYJW��ime
/////
35 strlen
IKXVKZOLKHLTKBFFTUZCYXHYVEBZOYJW���me
/////
36 strlen
IKXVKZOLKHLTKBFFTUZCYXHYVEBZOYJW����e
/////
37 strlen
IKXVKZOLKHLTKBFFTUZCYXHYVEBZOYJW�����

In other words it prints always ttime as the 31th character and then the code overwrites each character of that word and i get question mark as a result.

Going on the things get even worse look at the final output

100 strlen
IKXVKZOLKHLTKBFFTUZCYXHYVEBZOYJW�����K��ȶ������MKRLHALEV�SNNRVWNOEXUVQNJUHAEWN�W�YPMCW�N�PXHNT��0�
/////

Why does this happen?


Solution

  • Well you are printing garbage value. What the behavior will be is not known.(Undefined behavior) By that I mean, it may be the case that those garbage values (added with your random number) may be ascii values of some characters or may be those are some non-printables. You should initialize the char array (with \0's - that will serves two purpose, Providing \0 for the running string and also you can add and be sure it will be a printable) or just assign it.

    name[i] = 'A'+(rand()%26);
    

    Also put a \0 in the end of the string. Otherwise it will try to access array index out of bound until it finds \0 and it will invoke undefined behavior.

    31 is not something special - it can be anything the very next time you run it.

    Code:

    #include <stdio.h>
    #include <stdlib.h>
    #include <unistd.h>
    int main(void) {
        size_t i = 0;
        char name[100]={0}; // = "";
        srand(getpid());
    
        while(i<99) { // till 99 making sure you won't overwrite the last NUL
    
            name[i] ='A'+(rand()%26);
            printf("%d strlen\n", i+1);
            printf("%s\n", name);
            printf("/////\n");
            i++;    
        }
        return 0;
    }
    

    Note that we have looped till 98th index because there is NUL terminating character in the 99th index.