In this episode of “Did you know..?” we take another look at some C language tips.
- gets() function and strings
- Null terminating strings
- No break in switch statements
- == and strings
gets() function and strings
Don't use gets. gets() read a whole line of input into a string until a newline or EOF is encountered.
But YOU have to make sure that the string is large enough to hold any expected input lines.
If the input lines are to large, memory will be corrupted. Many security bugs are the result of gets. Use fgets() instead of gets().
Null terminating strings
In the C language a string is a character array with a terminating null character ('\0').
Some string functions (e.g. strncpy()) will keep processing data past the end of the character array (until it find a zero byte in memory).
Most C library string functions that create strings will properly null terminate.
No break in switch statements
The C language will not automatically break out of a switch statement if a "case:" is encountered.
You will have to put the breaks yourself, otherwish all the case statements will be executed.
It is not necessary to put a break after the last "case:" but is a good practice to do this anyway.
>== and strings
Never use the == operator to compare the values of strings.
The == operator is comparing the pointer values, not the data pointed to by the pointers.
Strings should be compared with the strcmp() library function.
(The file string.h should be included).