Why gets() is bad / Buffer Overflows
In this FAQ, you state that "gets() has only received the name of the array (a pointer), it does not know how big the array is, and it is impossible to determine this from the pointer alone."
However, it IS possible to determine the number of elements in any array by using the sizeof keyword, at least in tests that I have conducted in Microsoft Visual C++ and Borland C++ Builder.
For example, the following code prints the number of elements of the array, line twice. Once using this method and the other using the constant value that was used to declare the array.
Source:
#include <stdio.h>
#define MAXLINE 100
int main(int argc, char *argv[])
{
char line[MAXLINE + 1]; /* Extra element for null character. */
int printed;
printed = printf("%u %u\n", MAXLINE, sizeof(line) / sizeof(*line));
return (printed == 7 ? 0 : 1);
}
Output:
101 101