How to avoid buffer overflow in C/C++

Asked

Viewed 1,263 times

6

The program below allows the occurrence of memory overflow, as it is possible to overwrite the variable zero, placing a value "large" in the variable buffer. How to make a safe program by 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;
}
  • 1

    Watch out! It’s not guaranteed that this program will work (it’s even weird that it actually works). You are assuming an order of variables in memory that is no guarantee of the language. The compiler is free to rearrange them.

  • @Kahler, thank you!

1 answer

8


It is even simple, just use a more modern function that avoid bursting, she is the fgets(), where it can determine the size of the buffer and the function itself will protect the memory. For all purposes the gets() is considered unsafe and obsolete.

Enjoy and prefer the fputs() also, even if you don’t have the same problem.

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.