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.

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.

Extract of Programming

December 8, 2010 at 12:00 pm | Posted in Programming | Leave a comment
Tags: , , , , , , , ,

A colleague of mine once asked me a question: How to become a better Programmer ?. It was a small but brilliant question. Most programmers do not think of the answer which is correct. A correct answer will also tell you about the extract of programming. I have hanged on comp.lang.c for quite some time and I have always tried to learn as much as possible from programmers who are more intelligent and better than me. This has led to many changes in my belief-system on what is right way to program and what is the wrong way. Over time my definition of what are called fundamentals and basics of programming have changed, my practice of programming have taken an almost U-turn from what I used to do. I have become better and the very first sentence of the long answer to the question How to become a better Programmer or What is the essence (extract) of programming, will be Love. yes, good programmers, brilliant programmers love to program. They have certain kind of attitude that defines them, that separates them form the rest of void main()s.

I know you will say that everyone just can’t love programming. Yes, you are right. Trouble is, Indian education system does its best to not to let creative students love computers. The whole academic syllabus will be designed and selection of books will be done in such a way they will make any creative man to hate computers. You have to find your own way, you are on your own, thats bad news. Good news is once you determined to find your way then lot of people will help you, many of them you will never meet in real life. The community of these programmers, hanging out there reading code for hours can become your favorite pass time. Real programmers are very helpful friends, instructors and teachers. You will never be spoonfed, you will never be disrespected but only analyzed and encouraged to write good programs, programs that have quality. And one thing I have learned is that qulity comes from writing small programs, not big ones. I had a misocnception when I was a graduate student (most Indian students do have same) that writing big and complex programs will make you a better programmer, It will not (actually It will but its not true for beginners, you must already be good at basics to start writing big and complex software) Unfortunately most programmers have a weak basic and fundamental grouding in what they do. Here is the answer:

  • Write short programs. They will make you better. e.g. think what *p++ and *++p will do for a pointer p and what can be the result of *p++ = *++p.
  • Don’t just think, write code. Reading books will not take you anywhere. Knowledge alone is essential and it won’t make you a better programmer. Write code and write more code and write a lot more code.
  • Write code and read archives of comp.lang.c if you get problems. Most of the time solution will already be there. Don’t just ask for help. Search, read archives and if you can’t sit for hours reading archives and trying code, find some other profession
  • Hang onto you favorite language newsgroup. For C we have comp.lang.c, same for others e.g. comp.lang.lisp, comp,land.c++ etc. you can’t be a better programmer without hanging out there for a few years.
  • Be technical rather than personal on usenet. If someone says something that you don’t like because it goes against what you have learned from your school/college then please get over it. You are not in school anymore, its real world and hence things are done differently here, things are practical here
  • Rather than learning three or four new languages, give priority to learn basic algorithms and data structures. They are tough, yes, and they are very rewarding when it comes to solving real world problems (which is what you will do in a software job/business). This approach will save you not only from lot of suffering caused by Segmentation Faults but also happiness will come when you see how succinct, meaningful and readable your programs have become. Thats called maturity.
  • If you want to learn new language then learn something opposite to what you already know e.g. if you know C or C++ already then rather than learning Java, go learn Common Lisp, If you already know Python, then start learning learn Haskell, if you already know Perl, then learn Ruby to see how it solves the same problems. If you think you know already know a lot of programming then read Structure and Interpretation of Computer Programs and tell me how you feel :)

What I have written is based on my years of experience in programming. I have summarized my experience in a very small and short blog. Don’t just ignore it. I have done many mistakes as beginner and I don’t want you to waste your young years in walking a path and later realize that it was wrong. Youth won’t come again, save it, invest it to proper use. Programming is a kind of love difficult to leave once you got hooked onto living with it. Its a joy but a hard kind of joy :D


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.

The Programmer in Indian Corporate – 2

November 18, 2010 at 2:02 pm | Posted in Programming | Leave a comment
Tags: , , ,

In my earlier rant I talked about how Indian programmers are not interested in learning and sharpening their programming skills. I think did not do a justice by talking only about majority of them. There is a minority who is really interested in learning. What about them ?

There are programmers I have met (very few though, you know what minority means) who are interested in sharpening their craft, who are interested in learning programming but the organization does not support such kind of environment. Most MNCs in India do not provide an environment where a programmer can learn basics of programming, they never ever talk to their programmers on why Niklaus Wirth said Algorithms + Data Structures = Programs. All of them are made busy to meet deadlines, and they have to do it else they will loose their jobs. No one wants to loose his job. There will be hundreds of programmers working on one project and almost 80% of them never know what other one is doing. There will be less than or equal to hundred source code files and those 120 or 100 or 200 programmers will be working on them and on the top of that project manager will not be knowing which data structure (in conjunction with what algorithm) was used for solving the problem and then companies wonder why their proprietary software is called crap quality by programmers who have Open Source mindset. Programming is about solving problems, solving them in a smart way, solving them with an attitude of diligence and contemplating over small, very small and very tiny parts of code. Big parts, big things do not matter when it comes to problem solving in programming (coding). If you think you should have big programs, big files and need big teams to make a fine piece of software, you are wrong. Companies already have hired hundreds of programmers, dividing them in teams and then managers are managing them like a herd of cows and they are making software this way since the inception of word software. No wonder they still have problems they were getting 20 years back, testing pahse of the code written by those hundreds is 5 to 10 times more than the coding phase. What a shame. How much it costs ? The more you do it, the more the price of end product is going to rise. You have two solutions for this problem

  • MBA solution:
  • Filter all the empoyees based on some stupid tests taken from some books that teach wrong ways of programming. Fancy name is cost cutting, real name is jackassing in action.

  • Technical solution:
  • Provide an environment for programmers to learn, to sharpen their programming skills. Fire the current manager (especially if he has MBA degree) and hire technical one, he will do the job better. Ask programmers why Niklaus Wirth said Algorithms + Data Structures = Programs. Fire all those programmers who are not willing to learn. If you are a opening a new division of the company, then rather than hiring 100 programmers, add the salaries of all 100 programmers, divide it by 4 and hire 3 programmers, like Richard Heathfield, Pascal Bourguignon , Victor Bazarov, Edi Weitz, H. S. Lahman or Neil Walfield. Pay them that 3 units of ‘100 divided by 4′ salary and get a piece of software which your 1000 programmers team can not create in a thousand years and I bet on that. Don’t forget Arnuld Uttre for 4th position =:o)

Many managers and programmers may (and will) think that I am talking of crap solutions. Well, You can think anything you want and I speak from experience. I talk real, I write facts. Companies who pay salaries/bonuses on who wrote more lines of code are simply wasting their resources, pay more to them who write less code. Real programs are succinct and short: for(;;) *p++ = *q++ . In India, there are too many talented programmers who are living their lives on tiny financial amount they get. There are programmers who write crap and get 10 times more salary than the real one. There are very talented programmers who are doing odd jobs because they can’t get a programming job. Whether you agree or not, a quality piece of software will always be created by a programmer who has a solid grasp of algorithms and data structures and if you don’t have such kind of programmers then, either you or your management have sheep mentality, just like everyone else.

 

 


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.

My friends will kill me

February 24, 2009 at 7:15 pm | Posted in Hacking, History, Patterns | 11 Comments
Tags: , , , , , , , , , ,

Its been more than a year (since 2007) that I am using a a Linux distro running on text-based system configuration. The idea was difficult to adopt in the beginning but it look intelligent to me. So friends here is my Linux box running on Arch . There is no way you can edit any network or printer configrations from the Administration menu of GNOME in Arch. If yuo want to configure then go edit the text file. My colleagues who are still using Ubuntu struggle with the unknown and unrasonable problems everyday but they stick to Ubuntu, its Administration menu, the GUI based system to configure the system settings and they are stil there. Even after several years of usage they get mentally handicapped when some problem arises. They ask stupid questions to each other. Here is some conversation:

Ubuntu User 1: My system is not booting properly in Ubuntu. What should I do ?

me : whats the problem ?

Ubuntu User 1: I don’t know, Ubuntu is showing some error.

me : What kind of error. Is root file system geting mounted.

Ubuntu User 1: I don’t know.

me : Let me check

Ubuntu User 1: Don’t worry, I will reinstall Ubuntu.

Later I found out, fsck was showing some error on mounting /home partition and was throwing the user into maintenance shell to do fsck but he kep on pressing the Reset button instead.

Ubuntu User 1: I have Ubuntu but I need to play 3D games. Ubuntu does not play them as good as Windows XP.

Ubuntu User 2: Install Sabayon, you can play good games on it.

me : What playing games has to do with either Ubuntu or Sabayon (or even Debian) ?

Ubuntu User 2: Debian does not have any games.

me : Debian has largest collection of packages among all the distros. You only need to install a game using apt-get. Even if the package is not there, then you can download and install it.

Ubuntu User 2: With Debian I have to configure GNOME manually to run, eve after install it. I don’t want to configure GUIs.

me : Debian comes auto-configured. You just install something, e.g. X, and it configures it automatically.

Ubuntu User 2: No, Debian does not play games.

I really don’t understand this, if there is Open Source game, and the package is not available for Debian then you can compile it form source. But my friend does not say that he can’t compile, he says “Debian does not run games”. See the difference ?

Ubuntu User 1: I will not use Fedora, my sound system does not work in Fedora. It works in Ubuntu. So I will use Ubuntu.

me : your statement does not make any sense. Both Ubuntu and Fedora are Linux distros, you can check the sound module of your card and load it in Fedora.

Ubuntu User 1: you don’t want listen to me. I said, there is no sound coming in Fedora.

me : you need to run the lspci to check for what hardware you have and the see lsmod on Ubuntu to know the name of the kernel module being used for sound. Also check for Linux kernel version.

Ubuntu User 1: I will ask some one else who can solve my problem, you just don’t understand it.

Ubuntu User 2: Why go so deep into Linux. He can just reinstall Ubuntu if he gets problems.

… and they got angry. No.. I am serious, they are angry now.

I can show you thousands and millions of Linux users like this, who don’t want to know how to solve problems . First I thought, they don’t like the black screen of command line (I too don’t like it) or even the white background of X-terminal (which I do like), then I thought no one likes to type some words, you just need a mouse click and even these days companies are creating mouses with which we can type characters using clicks. Then I came to know the problem is more fundamental than Linux issues. The problem is of pain, finding the cause of some problem is a painful process (whether Linux or real life), even when you want to build a new house or put the wash-basin at some place in yoru house , it takes some amount of understanding and familiarity with how the houses are constructed and used by people. Putting time into understanding the house when your retired Father is finally building his sweet home , takes energy and the ability to take pain (mental exhaustation ?). All of colleagues are not running away from Linux, they are running away from pain the Linux gives. No one wants pain, everyone wants joy. Yeah.. me too. I want happiness and peace of mind.. the joy of life. The why do I believe in struggling with problems in Linux for days and nights when a 45 minutes Ubuntu reinstall will solve the problem. Why do I get into pain ?

To answer that question I have to go back to my earlier days, the day before I even installed Linux, the day my friend Dinesh mentioned the word Linux to me. Its all about happiness. So let me answer the question I have aksed: Why did I install Linux, because I trusted my friend, I knew he is intelligent than me, Its matter of friendship, the trust and respect you give to your friend based on his ability to creeate angels and daemons on hardware. Moreover I accepted my incompetence in front of him. Dinesh knew it wil be painful for me (a typical Windows User) to install Linux but he never helped me, he never said that he will want to help me. It was like the Cat’s kid, the Cat does not pick up her kitten when he falls while walking on some fence. She does not help her children because she wants them to learn to face the reality of life (quite in contrast to Human Mothers). I think thats why Cats grow out to be so intellgent. It is natural process of how cats grow their kittens. Kitten feels pain but that is required to successfully walk the fence, he needs training and his Mother gives him proper. Same way Dinesh behaved like. In the World of Linux, he was Cat and I Was his kitten and he handled me well. I am proud of having a friend like him who belives in letting people learn themselves rather than spoonfeeding them, a typical Hacker behavior.

Now when I struggle with the problems for days, then I am learning, I am looking for the final happiness, the long-term hapinnes, rather the short-term happiness caused by reinstallation. My friends have based their Linux learning on short-term happiness, thats the whole point. Their definition of hapinnes and my definition of happiness are different. They want quick-fix (cocaine ?) and I Want to drink Milk for 2-4 years continuouly everyday becayse only after years of this daily routine I will be in a good health. Their source of happiness is 2 hours ( Bade Miyan Chote Miyan ?) , my source of happiness is solving problems ( The Money Masters ?). and thats the source of everyone’s way of living this life. If you are still reading, good and if you are still reading and understand it too, well, congratulations, you can be the one you want to become. As a final note, I have edited the subtitle that comes with Ubuntu:

Linux for Idiot Beings

or need I say: Linux for Windows Beings, for Windows and Ubuntu users don’t have any identity of their own, they have let Microsoft shaped their way of thinking about software. They are no longer original but just copies of the way the Windows is designed.

 

 


Copyright © 2006, 2007, 2008 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.

Next Page »

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

Follow

Get every new post delivered to your Inbox.