Archive for October, 2008

Optimizing Switch-Case Statements In C For Speed

Tuesday, October 28th, 2008

Subscribe To Our Feed | Follow Us On Twitter | Get Updates on Email

The biggest bottlenecks in making efficient code today are jumps or branches. You must have always heard of people telling you to use switch-case blocks instead of cascadin if-else’es. They were right, but partially.

This is because a cascading if-else block will check for each condition in each iteration until it reaches the correct one. On the other hand, switch-case blocks are “supposed to” (why supposed to, we’ll see just now) just execute the correct statement and move on.

Optimization Technique 1: Keep the case label values close and small (Answer to “supposed to”)

Actually switch-case statements are also many times changed into if-else cascades by the compilers. This happens when the case label values are too far apart and/or are spread over a fairly large range. If you have a small switch-case statement like below, then the compiler will generate a jump-table instead of the if-else cascade.

switch(a)
{
  case 0: /*do something*/
  case 1: /*do something*/
  case 2: /*do something*/
  case 3: /*do something*/
  default:
}

A jump table is like a “lookup table” or a “dispatch table”. You can assume that compiler creates an internal array of addresses. The array is indexed by the case lable values and the value at that index is the address of instructions corresponding to that case.

Optimization Technique 2: Place those cases first which are more likely to occur

(more…)

© Safer Code | Optimizing Switch-Case Statements In C For Speed

Liked this post? Get FREE Updates
Subscribe to RSS feed

Or
Enter Your E-mail ID below

Validating Untrusted Integer Inputs

Tuesday, October 21st, 2008

Subscribe To Our Feed | Follow Us On Twitter | Get Updates on Email

If you are writing a software which exposes APIs to be used by a third party, then first thing you have to do is to make sure that all the integers parameters have been validated. Every incoming value to your function should be considered as tainted. The function should validate the input value by checking it for all possible malicious value. After the function validates the input, then only any operation on the input value should be performed.

Consider the following code sample:

void func( int size )
{
 char* str;
 
 if(size > 0 )
 {
  str = (char*)malloc(size * sizeof(char*));
  size++;
  /**
  *some code to operate on this string "str"
  **/
  free(str);
 }
}

I am sure that by now, you would have identified some loop holes in this code. Now, a caller of this function can give different input values which might result in following flaws:

1) The function might get an highest input value which results in a large memory allocation for ‘char* str’ which the function never expected.
2) The function might result in memory allocation failure as there is possiblity of the system running out of memory.
3) The function might have an overflow issue due to an increment in input value which could have been equal to SIZE_MAX.
These scenarios might serve as a boon for a hacker and he/she can instigate either a denial of service or any other buffer overflow errors.

Now, Lets rework the above depicted code again.

#define MAX_SIZE_OF_STRING ( 100 )
void func( int size )
{
 char* str;
 
 if(size > 0 && size <= MAX_SIZE_OF_STRING)
 {
  if(str == null)
  {
   str = (char*)malloc( size * sizeof(char*));
   if(size < SIZE_MAX)
   {
    size++;
   }
   /**
   *some code to operate on this string "str"
   **/
  }
  if(str != null)
  {
   free(str);
  }
 }
}

Please try to notice few defensive points from the above given code.

1) We have defined a maximum size for the string. We need to do this to make sure that large chunks of memory do not get allocated. This will result in optimized memory usage and longer life of the program.
2) We have validated the input value for its range comparing against its minimum and maximum value. By doing this, We sufficed the purpose of defining the size of the string.
3) Again, we check the input variable size for its value less than SIZE_MAX (maximum value possible for an integer). By doing this, we safeguarded against an overflow. Now, the size variable can never incremented beyond the maximum value.
4) Checking for ’size > 0′ helps in making sure that non zero number of bytes are allocated in memory, in turn, saving us from memory corruption.

By adding extra defense checks or safeguards, you might contribute towards addition in code size. But isn’t it better to have a secure code rather than less code which is vulnerable to exploits.

The point I am trying to make is very simple and is not a great deal. Everyone of us know of it but we tend to ignore these minor things resulting in misuse of code. Keeping these small points in mind while coding and adding these defense checks or safeguards will definitely result in robust and secure code.

© Safer Code | Validating Untrusted Integer Inputs

Liked this post? Get FREE Updates
Subscribe to RSS feed

Or
Enter Your E-mail ID below

int main() vs void main()

Tuesday, October 14th, 2008

Subscribe To Our Feed | Follow Us On Twitter | Get Updates on Email

What would be the best way to start a blog that talks about building safer code? Yes, it would be to talk about the first thing you think when you start coding. The “main” function (as seen in C/C++).

We’ve been brought up with many different variations of this popular function. Some books/teachers like to write it as “int main”, some write it as “void main” and then there are some who make do with just “main”, forgoing the return type altogether. So, which one out of them is correct? Or does it even make a difference?

The answer to the 2nd question is “YES”. It makes a whole world of difference as in it could:

  • do nothing
  • or give you a compile time warning
  • or crash the program
  • or cause problems in your invocation environment

Now, we go back to the first question. Which is the correct form and why?
The answer is “int main” is the correct type for C++.
But for C, it is a bit tricky and I’d say “int main” is the recommended way.
The simple reasoning is “because the C and C++ standards say so”. (See this however, which is what is leads to a bit of confusion though and makes it implementation dependent in c)

But lets take a brief look at the practical reasons for this because you might wonder “My compiler doesn’t give me a warning for void main, so why should I care?” (If your compiler does that, then its time to switch to something else. Did I hear you are using a Microsoft compiler? ;) ).
(more…)

© Safer Code | int main() vs void main()

Liked this post? Get FREE Updates
Subscribe to RSS feed

Or
Enter Your E-mail ID below

And So It Begins…

Tuesday, October 14th, 2008

Subscribe To Our Feed | Follow Us On Twitter | Get Updates on Email

Thousands of sites around the interwebs are devoted to programming and producing code. But there is something missing. This “something” is actually the most important piece of the puzzle. This piece is about how “safe” and “efficient” your code is. There are programmers all over, but a very small minority is worried about finding all the loopholes in their code. Infact, most don’t even know there could be loopholes even as they start writing their program (more on this very soon ;) ). And many times, you’d see people creating a jet fighter for something that could be solved with a bicycle (although the pace would be vice-versa).

The problem here is that there are many things that are not taught in the schools, the knowledge might be out there on the internet, but either it is fuzzy, not properly explained or is plagued by just too much of information overload. You cannot imagine yourself (and everyone else around you) to sit in a week-long class and emerge a champion programmer. It has to seep in gradually.

So, this is an attempt to solve the problem. We’ll bring you the concepts to make your code a fortress. We’ll bring them at a gradual pace that gives you time to learn, understand, ask questions and imbibe them into your daily routines. The problems and solutions would range from the very basics and trivia to the most advanced. We’d concentrate mostly on examples through C/C++ with a bit of JAVA and others interspersed here and there when needed but most concepts learned could be as well applied to any language. We’ll not tell you how to program, we assume you already know, but we’ll tell you how to program efficiently and securely.

So, if you are a college goer, or a fresher just into the corporate world, or an experienced professional, we have something for you all, to make you so capable that you can take a running program and re-write it so that it runs for years without crashing, being exploited to death, or taking a ton of memory or cycles.

Enough talking now. As Linus once said “Talk is cheap. Show me the code.”. So, lets begin…

© Safer Code | And So It Begins…

Liked this post? Get FREE Updates
Subscribe to RSS feed

Or
Enter Your E-mail ID below