Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: let there be const

...

Code Block
bgColor#FFCCCC
#include <stdio.h>
#include <ctype.h>
#include <string.h>

enum {max_user = 1024};
enum {max_password = 10}; /* sizeof("password\n\0") */

const char* valid_user = "user";
const char* valid_password = "password";

int do_auth(void) {
  char username[max_user];
  char password[max_password];

  puts("Please enter your username: ");
  if (fgets(username, sizeof( username), stdin) == NULL) {
    /* handle error */
  }
  /* trim off ws at end, including newline */
  while (strlen(username) > 0 &&
         isspace( username[ strlen(username) - 1])) {
    username[ strlen(username) - 1] = '\0';
  }

  puts("Please enter your password: ");
  if (fgets(password, sizeof( password), stdin) == NULL) {
     /* handle error */
  }
  /* trim off ws at end, including newline */
  while (strlen(password) > 0 &&
         isspace( password[ strlen(password) - 1])) {
    password[ strlen(password) - 1] = '\0';
  }

  if (!strcmp(username, valid_user) &&
      !strcmp(password, valid_password)) {
    return 0;
  }
  return -1;
}

void report_error(const char *msg) {
  const char *error_log;
  char buffer[24];

  sprintf(buffer, "Error: %s", error_log);

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

int main(void) {
  if (do_auth() == -1) {
    report_error("Unable to login");
  }
  return 0;
}

...

Code Block
bgColor#ffcccc
void report_error(const char *msg) {
  const char *error_log = msg;
  char buffer[24];

  sprintf(buffer, "Error: %s", error_log);

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

...

Code Block
bgColor#ccccff
enum {max_buffer = 24};

void report_error(const char *msg) {
  const char *error_log = msg;
  char buffer[max_buffer];

  snprintf(buffer, sizeof( buffer), "Error: %s", error_log);
  printf("%s\n", buffer);
}

...

Code Block
bgColor#ccccff
void report_error(const char *msg) {
  printf("Error: %s\n", msg);
}

...