Last active
November 14, 2022 18:45
-
-
Save linuskmr/54975378848249bfad9c593b0e39bacf to your computer and use it in GitHub Desktop.
Reading a password into a finite buffer allows shorter prefixes to match as well — Live demo at https://cplayground.com/?p=koala-phil-cod
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Reading a password into a finite buffer allows shorter prefixes to match as well. | |
// Live demo at https://cplayground.com/?p=koala-phil-cod | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
int main() { | |
// The correct password is: | |
constexpr char const * const EXPECTED_PASSWORD = "1234"; | |
// ..but also try to enter '123456'. | |
// Since the read buffer only has length... | |
constexpr size_t MAX_PASSWORD_LEN = 5; | |
char password[MAX_PASSWORD_LEN]; | |
// ...we only read so many chars: | |
printf("Enter password:\n"); | |
const ssize_t bytes_read = read(STDIN_FILENO, password, MAX_PASSWORD_LEN-1); // Leave one char for null-terminator | |
if (bytes_read <= 0) { | |
// errno==0 if bytes_read==0 because of EOF, but too lazy to handle it separately | |
perror("read"); | |
return EXIT_FAILURE; | |
} | |
// Manual null-termination, because read() doesn't do it itself | |
password[bytes_read] = '\0'; | |
// Remove potential \n | |
password[strcspn(password, "\n")] = '\0'; | |
// The password in the buffer may be shorter than what you entered... | |
printf("Password stored in buffer: %s\n", password); | |
// ...so the comparision is true in more cases than expected | |
const bool password_correct = strcmp(password, EXPECTED_PASSWORD) == 0; | |
printf("correct? %s\n", password_correct? "true" : "false"); | |
// What did we learn? Use getline() | |
// Or avoid writing C and use Rust instead :) | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment