fix buffer overflow

This commit is contained in:
Chris Cromer 2018-11-12 18:29:51 -03:00
parent e3f5691462
commit ff70e7df27
Signed by: cromer
GPG Key ID: 39CC813FF3C8708A
1 changed files with 30 additions and 3 deletions

View File

@ -16,6 +16,7 @@
#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
#include "random.h"
#include "timer.h"
#include "bubble_sort.h"
@ -66,6 +67,34 @@ void print_array(int *array, int n) {
fprintf(stdout, "\n\n");
}
/**
* Leer el buffer de stdin y guardar el valor si es numerico
* @param variable Donde se guarda el valor del stdin
* @return Retorna 1 si es exitosa ó 0 si falla
*/
int read_buffer(int *variable) {
char buffer[12];
while (1) {
if (fgets(buffer, 12, stdin) != NULL) {
if (buffer[strlen(buffer) - 1] == '\n') {
buffer[strlen(buffer) - 1] = '\0';
break;
}
}
}
char **check = malloc(sizeof(char**));
long input = strtol(buffer, check, 10);
if (*check[0] == '\0') {
free(check);
*variable = (int) input;
return 1;
}
else {
free(check);
return 0;
}
}
/**
* Liberar la memoria al salir
*/
@ -180,9 +209,7 @@ int main (int argc, char **argv) {
if (elegir) {
opt = 0;
fprintf(stdout, "Elegir elemento %lli: ", i + 1);
while (!fscanf(stdin, "%d", &opt)) {
// Falló, pide de nuevo después de limpiar stdin
while ((opt = getchar()) != '\n' && opt != EOF) { }
while (!read_buffer(&opt)) {
fprintf(stdout, "Número invalido! Tiene que ser mayor de 1!\n");
fprintf(stdout, "Elegir elemento %lli: ", i + 1);
}