Strcat causes a segmentation error when simply entering a password of type getch

I use Linux, and there is a user-defined function that returns ASCII of the intcurrent key type like getch(). When I try to get used to it and how to store the password, I got into a problem, my code looks like this:

int main() {
    int c;
    char pass[20] = "";

    printf("Enter password: ");
    while(c != (int)'\n') {
        c = mygetch();
        strcat(pass, (char)c);
        printf("*");
    }

    printf("\nPass: %s\n", pass);

    return 0;
}

Unfortunately, I get a warning from GCC:

pass.c:26: warning: passing argument 2 of β€˜strcat’ makes pointer from integer without a cast
/usr/include/string.h:136: note: expected β€˜const char * __restrict__’ but argument is of type β€˜char’

I tried using pointers instead of a char array for passing, but the second I type the letter it segfaults. The function works on its own, but not in a loop, at least not like getch () on a Windows system.

What do you see wrong in my example? I like to learn this.

The EDIT: . Thanks to the answers, I came up with the following dumb code:

int c;
int i = 0;
char pass[PASS_SIZE] = "";

printf("Enter password: ");
while(c != LINEFEED && strlen(pass) != (PASS_SIZE - 1)) {
    c = mygetch();
    if(c == BACKSPACE) {
        //ensure cannot backspace past prompt
        if(i != 0) {
            //simulate backspace by replacing with space
            printf("\b \b");
            //get rid of last character
            pass[i-1] = 0; i--;
        }
    } else {
        //passed a character
        pass[i] = (char)c; i++;
        printf("*");
    }
}
pass[i] = '\0';
printf("\nPass: %s\n", pass);
+3
3

, strcat a char * ( ). , char.

c pass, int i, pass, -

pass[i] = (char) c.

pass, ( 0).

+3

, .

, "a" "a" - .

C - . "" 20 - , 20 .

mygetch() char.

, c .

"strcat (pass, c)" "pass [i] = c", , mygetch().

[i] = '\ 0', , , mygetch(), .

, c, , \n. mygetch(), :

int i = 0;
for (;;)
{
    c = mygetch();
    if (c == '\n')
        break;

    c = mygetch();
    pass[i++] = c;
}
pass[i] = '\0';
+1

strcat() - , ? , , , , EOF, "c" ( "\n", , , n ").

:

int  c;
char pass[20] = "";
char *end = pass + sizeof(pass) - 1;
char *dst = pass;

while ((c = getchar()) != EOF && c != '\n' && dst < end)
    *dst++ = c;
*dst = '\0';  // Ensure null termination

"mygetch()" "getchar()" - , , , "mygetch()"; , EOF.

, strcat(), , :

char c[2] = "";
char pass[20] = "";
char *end = pass + sizeof(pass) - 1;
char *dst = pass;

while (c[0] !=  '\n' && dst < end)
{
    c[0] = mygetch();
    strcat(dst, c);
    dst++;
}

, - strcat() . , , strcat(pass, c), , strcat() 0, 1, 2, 3,... . , , dst NUL , , strcat() . 1 , , , .

0

Source: https://habr.com/ru/post/1772977/


All Articles