Claudio Pisa Claudio Pisa - 3 months ago 20
C Question

C - Limit the string length

(Sorry for my bad english !)

I wrote a program that asks you to type a password no longer than a certain number, eight characters in this case. The characters that pass the limit will be cut out from the array:

#include <stdio.h>
#define MAXCHAR 8

main()
{
char password[MAXCHAR];
int i;
char c;

printf("Insert password: MAX 8 CHARS!\n\n");
for(i = 0; i <= MAXCHAR; i++){
c = getchar();

if(i == MAXCHAR){
break;
}
else{
password[i] = c;
}
}

printf("%s\n", password);
}


So the program works BUT there is a "strange" problem. If the limit IS EIGHT and I type a password longer than eight characters
(Example: P455w0rds98)
the output will be like this:

P455w0rd☺


So it puts a smiley at the end and I don't know why. It happens only if a the limit is established at eight.

Answer

You must specify the length to print or terminate the string. Otherwise, you will invoke undefined behavior. Try this, in which the latter method is implemented.

#include <stdio.h>
#define MAXCHAR 8

int main(void)
{
    char password[MAXCHAR + 1]; /* allocate one more element for terminating null-character */
    int i;
    char c;

    printf("Insert password: MAX 8 CHARS!\n\n");
    for(i = 0; i <= MAXCHAR; i++){
        c = getchar();

        if(i == MAXCHAR){
            break;
        }
        else{
            password[i] = c;
        }
    }
    password[MAXCHAR] = '\0'; /* terminate the string */

    printf("%s\n", password);
}

The if(i == MAXCHAR){ break; } part doesn't look good, so here is another code example:

#include <stdio.h>
#define MAXCHAR 8

int main(void)
{
    char password[MAXCHAR + 1]; /* allocate one more element for terminating null-character */
    int i;

    printf("Insert password: MAX 8 CHARS!\n\n");
    /* read exactly 8 characters. To improve, breaking on seeing newline or EOF may be good */
    for(i = 0; i < MAXCHAR; i++){
        password[i] = getchar();
    }
    password[MAXCHAR] = '\0'; /* terminate the string */
    getchar(); /* to match number of call of getchar() to the original: maybe for consuming newline character after 8-digit password */

    printf("%s\n", password);
}
Comments