Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why are there 2 extra characters always added to this string?

I am writing a program in C, where I generate multiple strings made up from random characters. Essentially the size of each string is fixed, set to be 8 characters, and a random character is inputted for every index of the string, accounting that the last index is the null terminating character.

However, whenever I go to print the strings, I get 2 extra characters added to them, and the strlen() function returns a length of 10 instead of 8.

This is how the output looks like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

image

And this is the code:

char password[9];
for(int cnt = 0; cnt < n; cnt++){
    for(int i = 0; i < 8; i++){
        if (i < 3){
            password[i] = rand() % 26 + 65;
        } else if (i < 6){
            password[i] = rand() % 26 + 97;
        } else if (i >= 6){
            password[i] = rand() % 10 + 48;
        }
    }
    printf("%s\n", password);
    printf("%d\n", strlen(password));

I tried to make a random string generator, I was expecting the string to be the same size that I set it to be.

>Solution :

char password[9]; declares an array that provides 9 characters worth of data, but it doesn’t initialize them to anything (unless it’s a static or global variable, that is); it’s got whatever garbage happened to be in the memory it occupies. You fill in 8 characters, and the 9th character is left uninitialized. When treated as a C-style string, if none of those characters are NULs, you read off the end of the array into adjacent memory, and keep going until it hits a NUL by coincidence (and decides it’s done), or reaches unreadable memory (and crashes).

To ensure it’s properly NUL terminated before treating it as a C-style string, either:

  • Change the declaration to initialize the characters to zeroes:

    char password[9] = {0};

  • or explicitly set a NUL terminator at some point:

    password[8] = '\0';

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading