3 ms·
1. Avoid sizeof, lest someone comes and changes the array into a pointer. Use constant parameter instead: #define BUFLEN 8 char buffer[BUFLEN]; strncpy(...et
by rini17 8y ago
1. Avoid sizeof, lest someone comes and changes the array into a pointer. Use constant parameter instead:
#define BUFLEN 8
char buffer[BUFLEN];
strncpy(...etc... BUFLEN-1);
2. Check length of the string to be copied BEFORE copying and if too long, fail (using assert, exit or so) instead of silent truncation or worse.
Why it is so hard and instead new "safe" string functions must be invented?
- kazinator 8y agoThere is no absolutely foolproof way to code in C such that no matter how someone changes the program, they will be spared from making a mistake. If we just program for today, sizeof buffer is much better than proliferating a preprocessor constant that may or may not correctly reflect the object being overwritten. For the silly mistake of changing an array to a pointer without taking care of sizeofs, GCC gives us some diagnostics: -Wsizeof-pointer-memaccess Warn for suspicious length parameters to certain string and memory built-in functions if the argument uses "sizeof". This warning warns e.g. about "memset (ptr, 0, sizeof (ptr));" if "ptr" is not an array, but a pointer, and suggests a possible fix, or about "memcpy (&foo, ptr, sizeof (&foo));". This warning is enabled by -Wall. -Wsizeof-array-argument Warn when the "sizeof" operator is applied to a parameter that is declared as an array in a function definition. This warning is enabled by default for C and C++ programs.