C++ new() operator

June 28, 2012 at 7:17 pm | Posted in C++, Programming | Leave a comment
Tags: , , ,

I was working on adding some features to a software written as a mixture of C and C++ and I came to realize many C++ programmers write C in C++. Take a look at this:

#include <iostream>
#include <new>

int main()
{
  char * t = new char[1];

  if(!t) 
    {
      printf("Memory Exhausted\n");
      exit(EXIT_FAILURE);
    }

  t[0] = 'A';

  printf("t[0] = %c\n", t[0]);
  return 0;
}

Everything looks fine and g++ (on RHEL 5) even compiles/runs with flags (-ansi -pedantic -Wall -Wextra) and without any warning/error. Program just seems to be technically correct (which it is seems like but isn’t) and prints the value inside array as expected. Now let us take a more basic look at this. Why we are using printf() in a C++ program when C++ has its own standard library ? The program we have writen is actually C in C++. It is like using a powerful mechanism and throwing all the powerful tools/methods away because you don’t want to know about them. Many industrial programmers don’t want to know about it because life goes on fine without knowing about it and they are still earning much higer salaries without knowing it (and they will keep on increasing their monthly income by impressing HR guys with a bag of languages and big projects on their Resumes). Hence Why bother ? Wrong reasons. If you are really looking for laziness then find it elsewhere because laziness equals to the amount of bugs in programming. Rewrite it the C++ way:

#include <iostream>
#include <new>

int main()
{
  char * t = new char[1];

  if(!t) 
    {
      std::cerr << "Memory Exhausted" << std::endl;
      exit(EXIT_FAILURE);
    }

  t[0] = 'A';
  std::cerr << "t[0] = " << t[0] << std::endl;

  return 0;
}

It is still not C++. What we call it now is a mixture of C and C++ provided the programmer does not know about C++ much. He was basically a C programmer and was either forced to use C++ compiler or was too lazy to know C++. Again it compiles/runs fine as it looks technically correct. check out new operator in section 18.6.1 of current C++ standard (you can check out draft of the standard, just google for N3337.pdf). new does not return NULL, hence the check is wrong. new throws bad_alloc() if it can’t allocate memory. Hence the technically correct version looks like this:

#include <iostream>
#include <new>

int main()
{
  char * t;

  try { t = new char[1]; }
  catch(bad_alloc)
    {
      std::cerr << "Memory Exhausted" << std::endl;
      exit(EXIT_FAILURE);
    }
  
  return 0;
}

This will never compile. Why ? Because you did not mention where bad_alloc is coming from. It is in standard library, hence you need to use std::bad_alloc. If you think you simply dump the whole standard namespac by using using namespace std in there, then you really need to read C++ FAQs before writing C++ programs any further. You need to think why I am writing std::cout instead of usual cout used by typical Indian programmers. Let us try one more time:

#include <iostream>
#include <new>

int main()
{
  char * t;

  try { t = new char[1]; }
  catch(std::bad_alloc)
    {
      std::cerr << "Memory Exhausted" << std::endl;
      exit(EXIT_FAILURE);
    }

  t[0] = 'A';
  std::cout << "t[0] = " << t[0] << std::endl;

  return 0;
}

This seems like pure C++. Yes, it is. Sure ? We still have one general programmig problem remaining to be solved. If you call exit() then you are not being practical, e.g. you wrote a client which connects to a server. One of the users of your software is connected and suddenly he is out of memory, then you program will just disconnect without saying a bye. Server will not like it and may log it as an error or will wait for an automatic timeout.

That was a general exmaple, let us look at more technical example. When a game adjusts your resolution to 640×480 and resets it back to normal (say 1280×1024), it will call destructor on 640×480 in resetting but it will not do so because exit() will not call the destructor, you will get stuck in a low resolution screen. It happens when some games crash without throwing an exception and rolling back the stack. So what do you do ? Let us try one last time to write pure C++ code :)

#include <iostream>
#include <new>

int main()
{
  char * t;

  try { t = new char[1]; }
  catch(std::bad_alloc)
    {
      std::cerr << "Memory Exhausted" << std::endl;
      return EXIT_FAILURE;
    }

  t[0] = 'A';
  std::cout << "t[0] = " << t[0] << std::endl;

  return 0;
}

NOTE: There is still a way if you want to check for NULL (instead of catch()ing an exception). You can use the nothrow version of new operator which returns a NULL pointer instead of throwing an exception but you have to mention it explicitly.

 


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.

one year vs four days

May 12, 2012 at 1:47 pm | Posted in Programming | Leave a comment
Tags: , ,

At my workplace I contributed to the creation of a software while working with systems programming team. It worked fine at that time. Last year new requirements were proposed, which, from my perspective, pressed the need for a fundamental change in design. Face the fact, Corporates are rigid, hence ideas of changes in design were postponed, postponed and the postponed more. Its same story everywhere in every corporation (except few ones). Company decided not to take the risk of making new changes and added new code to the current product at that time. And that spoke trouble many months later and screams were heard followed by pressures and tensions in few months after those “many months”.

During last week I was assigned the task of rewriting one part of that software, as managers got too much frustrated with the rigidity. I was given the freedom of doing whatever I wanted to do make problems disappear in 2 days (I told them I don’t know black magic and none of my friends know Voodo). I looked at old design and new requirements and hell I did not see any match. So I rewrote several (yeah, not one) parts of that softwares, almost 80% of the code was rewritten, tested and given back in 3 days flat.

Whats so important in this ? The software which took one year to write, I rewrote 80% of code in 3 days, edited makefile and compiled the source and ran it and it did not segfault. Holy Cow… it was really black magic. Everything gave correct results while I tested it for 4th day. There was only one problem of a mutex lock was not opening. Whats the lesson ?

Experience, listening to experts in field and using methods, tools and techniques advised by those experts. No one is master in this world (especially no one becomes a master in 4 years) you have to share and learn from programmers around, provided those programmers really work hard on writing correct code. If you can’t find such programmers around you, google for usenet newsgroups, IRC channels, check comp.lang.(your language). Earlier when I contributed I was a newbie and now after 4 years I see I have developed the skill to solve problems in a fast and efficient manner. If I knew algorithms and data structures better than what I know now then I could have done much better job than 4 days or produced much more requirements-matching code. When a function is wrong then you can rewrite it. When a data-structure is wrong then you have to rewrite the data-structure and all the functions associated with it, which means 100% rewrite, which is what I did and I removed the rigidity of that software. It was pretty hard and the result was astounding.

Other lesson is to make sure your requirements are specific, not general. Instead of saying “We want to add/remove/find elements as efficient as possible”, one needs to ask “We want to add/remove/find elements based on a unique keyword.” Ask questions: Removals are more or additions ? “You want to sort the input or not and why ?”. “What exactly the input is and what exactly the output is, which requirements can match which data structure.” “Which operations are important and which are not.” “you want it to eat less memory or cpu and why” etc. etc.

This experience makes me both sad and happy. Happy because I can see specialized methods, tools and techniques of programming can save huge amounts of time. Sad because I am still far behind those methods. No wonder companies like Google/Microsoft/Facebook are ruling the world. They hire programmers who have mastered the art of these techniques/tools/methods. I still don’t know how to write a Red-Black tree using pointers. I still don’t know how to make it cpu-efficient or memory-efficient. Do we sort a red-black tree ? Saddest part is none of the interviews ask any questions of these type. All of the friends I know have never been asked any questions on algorithms/data-structures. Without them you can and will put lots of rigidity, headache in shipped code and build your future-tensions as inherent property of the software. When will you learn timesort ? (Tim Peters created timesort for use in Python Programming Language. go google immediately).

NOTE: As a business-owner/manager you must be thinking what is the business use of all these specialized techniques/methods and tools of programming ? Whats it in for me, Need I not make money ? I need to produce results as manager. Well, I am telling you since you are asking (or will ask): these are invaluable and useless, depending on your attitude. If you want your problems to be solved faster and better then use them. If you want to be better than your competitors then use them. If you don’t want to handicap yourself by solving same kind of problems for next 10 years but will really be happy to solve differet kind of business problems and make more money each year then please use them. And if you don’t want to accept that algorithms/data structures can help you then please don’t. Earth was always moving around Sun even when whole world believed it did not. I can’t help if you don’t want to listen to Joel Spolsky (I am writing in bold that he is a businessman) and Guy Steele and loads of others. In fact no one can help you then. (By the way, everyone knows Guy Steele)

 


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.

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 langauge and thats it. They think learning more languages will make them better programmer. Unfortunately this is not true.
  • New Paradigm : Other experiences programmers want to learn a new paradigm which will change their way of thinking and make thema better programmer rather than a programmer who knows several languages. He thinks that learning a language like C++ wil automatically make him an OO expert. Sigh…. he got immature mindset too.
  • Reality Check : No matter what a programmer wants to do, either of the above or both, his thoughts are crushed by the reality of the software as an industry. He works whole day and then he has a family and he wants to have a life too and there are only 24 hours in a day. Out of all this mess and busy schedule, he starts thinking that he can not afford to spend time learning a langauge which does not give him a rise in his income.
  • RealProgrammer : . Now there is another breed of programmers, which I call real programmers (I am one of them. What you think ? … No ? … c’mon just believe it because I am the author of this post ;) ) Here the real programmer, I mean the one who does not believe in quick fixes, the one who started programming because he likes it, because he is happily willing to live next 20, 30, 40, 50 years of his life writing code, THAT ONE decieds to go long term. Rather than deciding on income-factor he goes with programming-factor, he decied to learn new-paradigm, decides 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 skill as programmer. I think you must aim for getting more out of the time you spend, you must aim differently, you must aim what your common-sense thinks is right. Unfortunately most programmers don’t have that common-sense because industry is full of programmers who do it for money just like a fruit-seller who sells fruits for money but himself does not eat much of them because he is not interested in how fruits lead to good health. My advice will be wathcing and observing what all brilliant programmers are doing from years and learn from them. Thats what I do.

I am a C Programmer and I wanted that new language to help rise in my career too. Of course the choice came out to be C++. But C++ is almost in the same paradigm as C plus more. C is procedural while C++ has OO and generic paradigms added to and it is designed in such a way that you can add a lot of other paradigms to it but C and C++ belong to almost same kind of mindset. I wanted to write a microkernel for Hurd, hence I dwelled into other languages like BitC and decac etc. but then again lack of time and my focus on what can I do to become better programmer and use my time with maximum productivity. Here are the options I think I have found:

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

Now, I can’t learn everything, it will take 2 lives to finish this list off. So after lot sof googling, lots of readings of practical views, research papers etc etc I selected Common-Lisp. Lisp is 2nd oldest language still in existance 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. You must learn both C and Common-Lisp if you are serious about programming.) For Managers Common-Lisp has OO and the next generation fancy (but practical) words e.g. MOP (Meta-Object Protocol if you have never heard of it). There are lot of strange languages and I don’t know why Common-Lisp impressed me so much. So far I have seen only one company in India using it.

Bottom line is: If you want a job, learn Java, C#, .NET or C++ . If you want to be a better programmer and willing to spend next 20 years of your life writing code, you better learn C and Common-Lisp and yeah arrays and pointers are not same and code is data in Lisp. The point is not to run after money but specizlized skills in programming. Specialized skill over long-term attracts money automatically.

 


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.

Simple Lessons

May 12, 2011 at 10:33 am | Posted in Patterns | Leave a comment
Tags: , ,

I am working in C from last 3 years and these two very simple lessons are based on my experience, these are not taken from any book but by my own understanding of programming. They may look very simple and short and don’t underestimate them. You may already know them (I did) and you may not be aware of them. Its like everyone knew that apple falls on the ground but only Newton became aware of it :)

  • Solving Problems: Programming is all about solving problems. I knew that (and I am sure you knew that too), every programmer know this but how many programmers translate business problems into code? May be you are working on the problem which is just your interpretation of the problem? What is the real business problem you are trying to solve on your job as a programmer? You are actually a translator between a business man and computer.

  • Diagrams: Before you even think about coding you must draw a digram on how you are going to split this business problem into some or lots of small ones and what will be the general idea behind solving this problem. That you can accomplish very effectively by drawing a diagram on paper using a pen (or pencil). Also known as DFDs (Data Flow Diagrams). You will see how much of your life has become easier with DFDs. DFDs follow some rules and you can make your own diagrams and your own rules but make sure you stick to some standard (whether your own or someone else). DFDs are designed to make your life easier, it will make you happy because once you start coding you will see how important they are.

  • Tools: What tools you are using to translate problems into code ? Whether you are solving business problems or you do it for joy of solving problems (in the world of Hackers), Algorithms and Data Structures are the first of the tools you need, programming language is 2nd tool. Majority of programmers do not focus on first tool. Why you need qsort() over other sorting techniques. Why AVL tree will be better than Red-Black tree or Binary-Search tree. Why you will use a circular linked list instead of a doubly-linked list implemented as a Stack ? Why there exist so many different kind of trees and linked lists. Even I, myself, know only few of them. Its hard work but surely simple and very rewarding. I think half of the bugs exist in software because programmers lack this tool or the intended use of it

  • Tools-2: Like I said, programming language you are using is 2nd tool. Don’t go to high level talk here or dig yourself into advanced programming before you understand the basics. I use C language, so before I go into advanced C book, I will make sure I have spent two years on comprehending C FAQs and comp.lang.c archives

  • Breaking a big problem into small problems: I am using C, which is a procedural programming language. Hence I break down a business problem into small procedures (also known as functions). I will make sure that when one procedure calls other then both of them are doing some specific work and that in a proper and structured way. Writing too many procedures or the ones which do not have a proper siginificance can (and will) cause semantic bugs which in turn cause headaches over time.


Copyright © 2011 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.

Broken Binary Search

December 28, 2010 at 4:59 pm | Posted in Programming | 1 Comment
Tags:

While randomly googling for binary search, I came across this article where author (I guess one of the employees of Google) says that nearly all binary searches are mergesorts are broken. I don’t know much about Java but here is what he is showing on his blog:

1:     public static int binarySearch(int[] a, int key) {
2:         int low = 0;
3:         int high = a.length - 1;
4:
5:         while (low <= high) {
6:             int mid = (low + high) / 2;
7:             int midVal = a[mid];
8:
9:             if (midVal < key)
10:                 low = mid + 1
11:             else if (midVal > key)
12:                 high = mid - 1;
13:             else
14:                 return mid; // key found
15:         }
16:         return -(low + 1);  // key not found.
17:     }

Author says line 6: int mid =(low + high) / 2; is broken because if sum of low and high is greater than INT_MAX then it will overflow. From author himself; This bug can manifest itself for arrays whose length (in elements) is 2^30 or greater (roughly a billion elements). This was inconceivable back in the ’80s, when Programming Pearls was written, but it is common these days at Google and other places. He is right and I am not posting this to say what has already been said. I am interested in line 3: int high = a.length – 1;

Like I said I don’t know much about Java and if we write same line of code in C, it will overflow if a.length is long, unsigned long or anything larger than what size_t type can handle. It will give strange results (UB or Undefined Behavior). If having more than size_t elements is common for places like Google then I think line number 3 needs to be the cause of concern too, not just line number 6. You can know size of array in C with these methods:

const char* arrc = “123″;
int arri[] = {3,2,1};

first is an array of characters while 2nd is an array of integers. You can use sizeof(arri) / sizeof(arri[0]) to know number of elements in arri. To know number of elements in arrc you can use either strlen(arrc) or sizeof(arrc) / sizeof(*arrc) – 1. Both sizeof and strlen() return size_t type which is unsigned int and hence does not fit in int type. I have commented this on that blog, lets see what author says.


Copyright © 2010 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.

Copyright does not belong to Java code. Please ask for permission from the author of the following blog before using mentioned Java code: http://googleresearch.blogspot.com/2006/06/extra-extra-read-all-about-it-nearly.html

Next Page »

Blog at WordPress.com. | Theme: Pool by Borja Fernandez.
Entries and comments feeds.

Follow

Get every new post delivered to your Inbox.