How to avoid buffer overflow in C / C ++

5

The program below allows the occurrence of memory overflow, because it is possible to override the variable zero by placing a "large" value in the variable buffer . How to make a secure program by avoiding 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;
}
    
asked by anonymous 05.08.2016 / 04:04

1 answer

6

It's even simple, just use a more modern function to prevent overflow, it's the fgets() . , where you can determine the size of buffer and the function itself will protect memory. For all intents and purposes the gets() is considered obsolete.

Enjoy and prefer fputs() too, even if you do not have the same problem.

If you use C ++, you have other options as you see in the question. Depending on the case a cin might be more appropriate. You have several data entry and exit functions .

    
05.08.2016 / 04:12