0

Ive got 2 example codes, one is safe against buffer overflows even compiled with gcc -fno-stack-protector -fno-pie -m32 save.c -o save

Code of safe program:

#include <stdio.h>

char check[16];

int main(int argc, char **argv) {
    printf("Enter a string: ");
    gets(check);
    printf("%s\n", check);
    printf("Accepted.\n");

}

Code of unsafe (vulnerable) program:

#include <stdio.h>

int main(int argc, char **argv) {
    char check[16];
    printf("Enter a string: ");
    gets(check);
    printf("%s\n", check);
    printf("Accepted.\n");

}

Why is the char outside the program "safe"? (in my case)

Barmar
  • 741,623
  • 53
  • 500
  • 612
BitFriends
  • 379
  • 5
  • 18

1 Answers1

1

In the first case you're declaring a global variable. This is generally a bad habit to get into for a multitude of reasons, many of which you'll discover over time, so it's best to never do that unless you have no other option.

The second case makes it local to main().

Even better is to make a function that performs the get-assign operation and returns char*.

It's worth noting that in both cases nothing about this program is safe as you're using a comically tiny buffer (16 bytes!) and never use a function that's buffer-length limited. gets is one of the worst to use. Consider something else, anything else, even scanf('%15s', &check).

Moving the buffer from one location to another doesn't make it any safer. The problem is with the buffer and how it's used.

tadman
  • 208,517
  • 23
  • 234
  • 262