Code from IBM

June 4, 2012 at 3:28 pm | Posted in Uncategorized | Leave a comment

I got the job to fix Segmentation Fault somewhere. While I was searching for strftime(), localtime(), ctime() , localtime_r() etc and their behavior with with multi-threaded programs (POSIX threads), I came across this piece of code from IBM. you can find it here [defunct]. I have a screenshot too 🙂

#include <stdio.h>
#include <time.h>

int main(void)
{
     char s[100];
     int rc;
     time_t temp;
     struct tm *timeptr;

     temp = time(NULL);
     timeptr = localtime(&temp);

     rc = strftime(s,sizeof(s),"Today is %A, %b %d.\nTime:  %r", timeptr);
     printf("%d characters written.\n%s\n",rc,s);

     return 0;
}

/*************************************************
     The output should be similar to:
     46 characters written
     Today is Wednesday, Oct 24.
     Time:  01:01:15 PM
************************************************************/

This C program is not correct. Do you see anything wrong with code? What is it? Do you see anything wrong with calls of localtime() and strftime()? Return values from them are not checked:

  • localtime():

Returns NULL when some error occurs. You pass this NULL to strftime() and whoaaa.. you got undefined behavior.

  • strftime():

Even if localtime() behaved correctly strftime() can return with an error condition. IBM’s code does save return value but again does no check of it. Program is simply printing array passed to strftime() without checking if return value was zero or not. Man page of strftime() says:

The strftime() function returns the number of characters placed in the array, not including the terminating null byte, provided the string, including the terminating null byte, fits. Otherwise, it returns 0, and the contents of the array is undefined. (Thus at least since libc 4.4.4; very old versions of libc, such as libc 4.4.1, would return max if the array was too small.)

Now if the contents of array are undefined then behavior of program is undefined too because you are trying to print an array with undefined contents. It can cause crash (if you are lucky), it can print garbage (you are still lucky) or it can just work fine printing the time because most of the time there will no error and that is bad-luck because it might work when you are using it but it will definitely crash when client is using it. So what we do? Just two simple checks:

#include <stdio.h>
#include <time.h>

int main(void)
{
     time_t temp;
     struct tm *timeptr;

     temp = time(NULL);
     timeptr = localtime(&temp);

     if(NULL == timeptr)
       {
	 printf("Error localtime()\n");
       }
     else
       {
	 int rc;
	 char s[100] = {0};
	 rc = strftime(s,sizeof(s),"Today is %A, %b %d.\nTime:  %r", timeptr);
	 if(0 == rc)
	   {
	     printf("Error strftime()\n");
	   }
	 else
	   {
	     printf("%d characters written.\n%s\n",rc,s);
	   }
       }

     return 0;
}

/*************************************************
Compiled on Linux:

/home/arnuld/programs/C $ gcc -std=c99 -pedantic -Wall -Wextra ibm.c
/home/arnuld/programs/C $ ./a.out
43 characters written.
Today is Monday, Jun 04.
Time:  03:50:57 PM
/home/arnuld/programs/C $
************************************************************/

There is one more change. I have put variables in closest possible block (check out int rc and char s, it is because I don’t see the point of declaring them earlier and using them later. Local variables must be declared/defined in the closest block possible. Another difference is I am initializing the array with null characters (or filling it with zeroes) so that it does not contain any garbage. This is actually more of a matter of style, a personal thing rather than a rule to write correct programs in C. It does write correct program and its not required that you do same while the first change regarding keeping variables in tightest scope possible definitely comes under one of the methods of writing good C programs.

Copyright © 2012 Arnuld Uttre, Village – Patti, P.O – Manakpur, Tehsil – Nangal, Distt. – Ropar, Punjab (INDIA)

Verbatim copying and distribution of this entire article are permitted worldwide, without royalty, in any medium, provided this notice, and the copyright notice, are preserved.

Coding Horror

June 3, 2012 at 2:17 pm | Posted in art, Programming | Leave a comment
Tags: , , ,

Recently I was reading an article on coding horror which mentioned that most of the software developers who come for interview can’t even program and later I came across another article regarding phone screening interview and he mentioned Steve Yegge’s 5 essential phone screen questions. I looked at them and I thought .. whoaaa.. so easy. I was with my friend on his Windows machine and did not have access to some Linux machine. So I downloaded Bloodshed’s Dev-C++ compiler and typed this code and ran several tests, all in 20 minutes. (Bloodshed Dev-C++ version 5.2.0.2). I worked through several problems, enjoy my C code 🙂

/* (1) Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the
number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".

 (2) Write function to compute Nth fibonacci number

 (3) print all odd numbers between 1 and 99
 */

#include &amp;lt;stdio.h&amp;gt;

enum { LIMIT = 100 };

void fib(const int n);
void print_odds(const int limit);
void print_fizzbuzz(const int limit);

int main(void)
{
	print_fizzbuzz(LIMIT);
	printf("\n\n");
	print_odds(LIMIT-1);
	printf("\n\n");
	fib(20);
	return 0;
}

/* No int/unsigned-long overflow check */
void fib(const int n)
{
	unsigned long f0 = 0;
	unsigned long f1 = 1;
	unsigned long fnum = f1;
	int i;
	if((0 == n) || (1 == n))
	{
		printf("fib(%d) = %d\n", n, n);
		return;
	}
	for(i = 2; i &amp;lt;= n; ++i)
	{
		fnum = f1 + f0;
		f0 = f1;
		f1 = fnum;
	}

	printf("fib(%d) = %lu", n, fnum);
}

void print_odds(const int limit)
{
	int i;
	for(i = 1; i &amp;lt;= limit; i = i + 2)
	{
		printf("%d\t", i);
	}
	printf("\n");
}

void print_fizzbuzz(const int limit)
{
	int i;
	for(i = 0; i &amp;lt;= limit; ++i)
	{
		if((0 == i%3) &amp;amp;&amp;amp; (0 == i%5))
		{
			printf("fizzbuzz\t");
		}
		else if(0 == i%3)
		{
			printf("fizz\t");
		}
		else if(0 == i%5)
		{
			printf("buzz\t");
		}
		else
		{
			printf("%d\t", i);
		}
	}
	printf("\n");
}


Copyright © 2012 Arnuld Uttre, Village – Patti, P.O – Manakpur, Tehsil – Nangal, Distt. – Ropar, Punjab (INDIA)

Verbatim copying and distribution of this entire article are permitted worldwide, without royalty, in any medium, provided this notice, and the copyright notice, are preserved.

Project Euler – Problem 1

May 28, 2012 at 3:23 pm | Posted in Programming | 1 Comment
Tags:

Recently I came across Project Euler. I always had trouble with applying problem-solving thinking to problems. Someone on IRC somewhere told me that these are the toughest problem he had ever faced in programming. I think its a good test of anyone’s programming abilities:

/* Add all the natural numbers below one thousand that are multiples of 3 or 5.
 * version 0.1
 */

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
  int i;
  unsigned long s = 0;

  for (i = 3; i < 1000; i += 3)
    s += i;

  for (i = 5; i < 1000; i += 5)
    {
      if(i % 3) s += i;
    }

  printf("%lu\n", s);

  return EXIT_SUCCESS;
}

After you solve a problem and give correct answer, it shows in your registered account as solved and a link to the forum thread is also provided where you can see different kinds of solutions posted in different languages. It also shows how many people so far have solved the problem. That’s a good measure of your intelligence. I think you must go ahead and give Project Euler a try.


Copyright © 2012 Arnuld Uttre, Village – Patti, P.O – Manakpur, Tehsil – Nangal, Distt. – Ropar, Punjab (INDIA)

Verbatim copying and distribution of this entire article are permitted worldwide, without royalty, in any medium, provided this notice, and the copyright notice, are preserved.

Must Reads – 1

March 23, 2012 at 4:59 pm | Posted in Hacking, Programming | Leave a comment

I started learning programming in year 2005. After I quit my sales job in February of 2005, I purchased Red Hat Linux Bible in end of April same year. It has been 5 years since then, I learned a lot about computers and it became my passion since then, all possible because of GNU, different Newsgroups, mailing lists, forums and all the helpful people. I have read many articles and books and essays and history of UNIX, Linux, GNU, BSD, Debian, and many other organizations and groups. Based on my experience I am providing here a list of articles that every computer science student, every programmer must read.

Ideal process would be to just read these links and google for extra information:

I guess in 1996 I tried to learn English from a book which you can find on every corner of India and it boasts to teach you English in 30 days. I tried and failed several times. Then 7 years later, during my graduation I tried to learn programming from a 30 days book and I failed again.

The problem was that these 30 days, 30 weeks, 10 days, 21 days books never teach fundamentals. Most of them have many unreasonable assumptions. By reading these you can only have superficial knowledge about these subjects and almost no knowledge of basics. This is so strange but I myself wanted to write an article like Teach Yourself “Martial-Arts/Car-Repair/Large-Scale-Electric-Systems/Nuclear-Physics/Fine-Arts/something-here/fill-your-favorite-words-here” in 10 Years.. At that time I never came across anything like blog, in 1996 there was no internet at my place, therefore I never wrote the article. Later I went into different kinds of jobs and forgotten about it. When I started learning programming and started my blog I wanted to write one but then suddenly one day I came across Peter Norvig’s Teach Yourself Programming in 10 Years and I was surprised. I concluded I will not write any blog post about my experience because people will think I am copying Peter Norving, trying to imitate him. So I dropped the idea but in the meantime before internet came I shared my experience of 30 days books with my friends.

The list of books and articles above is exactly opposite of those 30 days books. Enjoy 🙂

Copyright © 2010 Arnuld Uttre, #331/type-2/sector-1, Naya Nangal, Distt. – Ropar, Punjab (INDIA) – 140126

Verbatim copying and distribution of this entire article are permitted worldwide, without royalty, in any medium, provided this notice, and the copyright notice, are preserved.

The Real Programmer

March 19, 2012 at 11:04 am | Posted in Programming | Leave a comment
Tags: , , , , ,

I was checking out what new language to learn. There are several points here:

  • Language: Most newbies or less experienced programmers think of learning a new language and that’s it. They think learning more languages will make them better programmer. Unfortunately this is not true.
  • New Paradigm : Other experienced programmers want to learn a new paradigm which will change their way of thinking and make them a better programmer rather than a programmer who knows several languages. This is actually a better approach. But if you think learning a language like C++ will automatically make you an OO expert. Then you will end up no more different than the programmer who knows many languages

You need to think from a different angle. Are you willing to live next 20, 30, 40, 50 years of your life writing code. Rather than deciding on the income-factor What if you go with the programming-factor. What if you decide to learn a new paradigm, decide to check out something unheard in industry but heard a lot from the mouths of good programmers?

Learning programming for income is like a adding one more language to your Resume and that stops right there and it adds not much to your skills as a programmer. I think you must aim for getting more out of the time you spend, you must aim differently. My advice will be watching and observing what all brilliant programmers are doing from years and learn from them.

So instead of C++ and Java why not look at one on the list here. Now, it might take two lives to finish this list off. So you need to choose one or two languages here.

  • Haskell
  • ErLang
  • Common Lisp
  • Python
  • Ruby
  • Ada
  • Caml
  • BitC
  • decac
  • Eiffell
  • RISC Assembly
  • D Programming Langauge
  • Prolog
  • C++

After lots of googling, lots of readings of practical views, research papers etc etc I selected Common-Lisp. Lisp is 2nd oldest language still in existence after FORTRAN. Lisp has a changed a lot since then. Code and Data are same in Lisp. Many concepts were developed first in Lisp and then in other languages e.g. garbage collection. You can write Lisp code which will write Lisp code, its like creating a new language yourself.

I learned about recursion in 7 days which I struggled to learn for 4 years with C and C++. I learned Binary-Search in 5 minutes which I am trying from last year to understand with C, in C you struggle more with how to write in C rather than the abstraction of the problem and its solution.

No wait, I am not attacking C, not at all. C is a great language to learn to know about pointers which Lisp intelligently hides. I think C and Common-Lisp give two very different paradigms of programming and if you are serious about programming, you should learn both. C is a lot closer to metal while Lisp is a lot closer to abstraction (e.g. Meta-Object Protocol).


Copyright © 2012 Arnuld Uttre, Village – Patti, P.O – Manakpur, Tehsil – Nangal, Distt. – Ropar, Punjab (INDIA)

Verbatim copying and distribution of this entire article are permitted worldwide, without royalty, in any medium, provided this notice, and the copyright notice, are preserved.

« Previous PageNext Page »

Create a free website or blog at WordPress.com.
Entries and comments feeds.