Stupid C Programming Errors to Remember

I often see the same typo-related errors and bugs popping up. Here are a few quick common causes.

    • Compile error
      error: statement with no effect
      Cause
      if (somecondition)
          somevar == somevalue;

      should be
      if (somecondition)
          somevar = somevalue; 
    • CppCheck error
      mismatchAllocDealloc
      Cause
      fopen’s should be fclose’d!
      myfile = fopen(filename, "r");
      ...
      close(myfile);

      should be
      myfile = fopen(filename, "r");
      ...
      fclose(myfile);
    • Compile warning
      warning: large integer implicitly truncated to unsigned type
      Cause
      #define myConst 0x0f
      void myfunction(uint8_t);
      ...
      myfunction(~myConst);

      GCC defaults to using 16 bit arithmetic so needs a cast to drop the higher bits:
      #define myConst 0x0f
      void myfunction(uint8_t);
      ...
      myfunction((uint8_t)(~myConst));
    • Compile error
      error: expected declaration or statement at end of input
      Cause
      Last function in the file is missing a closing brace
      void lastFunc()
      {
          ...
          return;

      should be:
      void lastFunc()
      {
          ...
          return;
      }


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s