How to avoid buffer overflow in C / C++

The program below allows the occurrence of memory overflow, since it is possible to overwrite the zero variable by putting a "large" value on the buffer variable. How to make a safe program avoiding the buffer overflow ?

#include <stdio.h>

main(){
    char buffer[8];
    int zero = 0;

    gets(buffer);
    puts(buffer);

    if(zero == 0){
        printf("Zero continua sendo zero");
    }else{
        printf("A variavel zero foi modificada");
    }


    return 0;
}
Author: Maniero, 2016-08-05

1 answers

Is even simple, just use a more modern function that prevent overflow, it is the fgets(), where you can determine the size of the buffer and the function itself will take care of protecting the memory. For all purposes gets() is considered unsafe and obsolete.

Enjoy and prefer the fputs() Also, although it does not have the same problem.

If you are going to use C++, as stated in the question you have other options. Depending on the case one cin can be more indicated. It has several functions for data input and output .

In C++20 it may be interesting to use another formatting feature.

 8
Author: Maniero, 2020-11-05 16:14:17