Did you know..? C Programming Language Tips 3

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).

This entry was posted in Programming Tips. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed. Tweet This! Tweet This! or use to share this post with others.

There is currently one response to “Did you know..? C Programming Language Tips 3”

Why not let us know what you think by adding your own comment!

  1. Amandeep Singh on June 5th, 2010:

    I just loved ur website.. You have posted so much content .. You guys are doing a great job..

    Thanks