Why every C or C++ programmer must know pointers
March 4, 2013 at 9:00 am | Posted in C++, Programming | Leave a commentTags: Hyderabad, Hyderabad local train, MMTS
Some computer science engineering students once asked me why it is so important to know about pointers in C and C++. They complained (and almost every computer programmer in industry complains) that pointers are so hard to learn and they can’t see why they should work so hard. I was travelling in MMTS (Local Train Service in Hyderabad). MMTS service uses several trains and compartments in few trains have a LED-Box where the name of railway station is displayed before train is about to reach the same. And here is how it shows railway station name sometimes :



Do you see the name there ? Those letters which look like boxes and Ys with tildes above on them are actually memory corruption rather than English language. Now I can guess the program must have been written in a language where programmer had to do memory management himself. Since it is a LED-Box, it must be a C or C++ prgram in embedded environment. This is a real-life result of not knowing how to respect memory constraints. My best guess is either prgroammer has some dangling-pointer in his code or he must have an array-overrun (a.k.a Buffer-Overflow). Imagine these situations:
- Your C++ program does financial transactions for some company e.g. distributing salaries to its employees and your program uses a dangling-pointer to set salary amounts. With this dangling-pointer the CEO might get salary of a blue-collar worker or vice-versa.
- Your C program is used in controlling a weapon like firing, pausing, continuous 20 seconds firing etc. With buffer-overflow gun may fire for 20 seconds continuously when you press pause.
- Imagine your C program controlls a satellite orbiting around Earth being controlled from base station somewhere on Earth. Memory corruption can cause satellite to move left instead of right or even stop its motion or may burn all of its fuel while it orbits non-stop at full speed around earth.
These are some of the not so serious consequences of not knowing pointers. So, if you want to write correct C and C++ code, learn howe to use pointers. Yes, they are hard to learn and more than hardness, pointers requires experience. It is a very useful skill that will reduce debugging sessions from days to hours. Kernighen and Ritchie said in the preface of their book “The C Programming Language” printed in 1978 that C wears well as one’s experiecne with it grows. When 2nd edition was printed in 1988 (affectionately known as K&R2) they said they still feel same about C with decade more experience. They had a point (they had pointers in those 10 years
). Experience makes a good C programmer and you achieve that by following the footsteps of masters. In order te be a brilliant C programmer, You need to follow brilliant masters. Start with c-faq.com
Copyright © 2013 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.
GNOME 3 – Reincarnation of User Interface
January 17, 2013 at 9:08 am | Posted in community, Programming | Leave a commentTags: free software, gnome, window manager
I am using Stumpwm from last 2 years and a month back I came to know about GNOME 3. Little bit googling will tell you the kind of harsh and brutal criticism GNOME 3 developers have received for their new ideas. MATE and Cinnamon have come out of that criticism to preserve traditional desktop look and feel. So what is this new interface in GNOME 3 ? Well you can read HIG (Human Interface Guidelines) of GNOME project, I am here to talk about practical aspects not mentioned anywhere but have come out of my own experience of using GNOME 3 for few minutes. I order to explain that you need to know something about dektop and window managers.
I am not a fan of desktop. I focus on work I need to do and then find methods to accomplish the task in an effcient and faster way without wasting time and energy. This way of thinking had pushed me from Desktop to virtual WMs (window manager), virtual and floating WMs and then to pure tiling WMs. Hence I travelled from KDE, GNOME and Xfce few years back to Fvwm, windowmaker and then to wmii, xmonad and now to Stumpwm and Ratpoison. Still I keep an eye on how different technologies develop in software world and that is how I came to know about new developments in GNOME 3. As per the viewpoint of an average user there are two kinds of interfaces you get on computer: an ugly, hard to use, anti-user black command line and a beautiful, cozy, pleasing and user-friendly graphical-interface a.k.a desktop . Almost all average “Joes” love desktop as it works faster for them (in fact, it is actually opposite). Come to Linux world, we have desktops too, unlike all those average Joes believing otherwise. A desktop usually has menus, folders, windows, icons, supports atractive features like drag and drop, openeing a document/file/folder by double-clicking etc. On Command-Line you have to type commands to do anything and you don’t get icons, windows, menus and or any fancy stuff requiring graphical interface. These are two opposing ways average Joe thinks computers are. Come to Linux world again, here we have X Window System on the top of which a desktop runs. X Window System is the first graphical interface. What I mean by that ? X is the base on the top of which any graphical interface (or GUI) runs as far as Linux is concerned. While Windows XP users only have one kind of desktop, Linux has several as per the likes and needs of the users, GNOME, KDE and Xfce etc. This kind of design gives a lot of flexibility, power and control to Linux users. Like I mentioned earlier a desktop environment consists of several components. Along with menus, icons, panel etc., it has a window manager and a file manager (check Wikipedia for full list). What most users want is to do the necessary work and then get on with life e.g one person wants to write an email and hence uses a browser, one wants to watch a movie, one wants to his office work and others just want to browse the internet and many want to do all of these (and that includes me too). So, they need something which is simple, helps them do tasks in an effective way and finishes tasks fast. That was my motto and that pushed me towards Linux after I was mentally tortured, made insane and almost killed psychologically by Windows’s virus problems, frequent slow downs, weekly-installations and loads of other crap that every Windows user has experienced. Coming back to Linux, now if there is a way to finish the tasks faster then that means current way of doing work must be inferior because if you already doing what is best then there is no way you need anything else. There is another way of saying this: you are doing tasks in an effective way and there is always room for improvement and there is lot of room if what you are doing is being done same way from a decade. . I think that is exactly what GNOME team was thinking when they were lying the foundation for GNOME 3. What is this new foundation ? For that I need to explain tiling WMs. In a tiling WM (I use StumpWM) there is no minimize/maximize/resize when it comes to your windows (when you open an application e.g a video player then it opens in a window. If you open 2 applications e.g. video player (lets say VLC) and a browser (lets say Firefox) then you got 2 windows, Firefox window and VLC window). In a usual desktop you can minimize/maximize/resize any window and each window will have buttons to do that including a button, which looks like leter ‘x’, to close the window, usually these 3 buttons are in upper right corner of a window). A tiling WM does not provide any of these facilities, windows will always be maximized and no buttons. Tiling WMs are based on concept that a user wastes too much time in minimizing/maximizing/resizing windows, changing their locations and sizes across the screen and they are right. Screen is divided into panes, like a Paned-Window, and you will have one window in one pane. There are no menus, no icons, almost nil mouse support (yes, no left-right clicks and tricks), tiling WMs are keyboard driven. You want any application then know its name and run it as a command and you will not waste your time in trying to find it inside menus or searching pseudonym driven icons/shortcuts and finding where that shortcut points to when you accidentlly loose one. When you sit in front of your computer then most of your attention should be on your work, not on distractions and pure tiling WMs make you do exactly that.
Sadly almost all people use desktops and waste their time and energy on icons, menus and mouse-clicks. Whole software industry is based and competing on who gives more desktop-eye-candy. Like high-school kids, users keep on eating those candies and spoil their teeth (brain in our case). Tiling WMs have a short learning curve and that takes some time (toook me a month to replace my desktop with StumpWM) and not everyone likes empty screens and black backgrounds. So, something was needed which could bring the usability of tiling WMs and pleasing-candy feelings of desktop under one roof and that is what GNOME 3 did. you can’t minimize a window in GNOME 3 ()it does not have those buttons) and it has no panel. Each Window is maximized, It does not have right-click menu on desktop. GNOME 3 does not have a menu and you can still find list of all of your applications and settings there, it does not have Home icon but it possesses a file manager for your tasks. GNOME 3 has been criticized by lot of people, even Linus Torvalds finds it a mess . I say GNOME 3 will change the way desktop will be looked at and used, GNOME 3 has redefined the word usability and it has put that word back into desktop. It has combines the effectivemess, speed and usability of tiling WMs and user-frindliness of desktops. There are many desktop UIs already developed for your desktop computers and many will be developed in future. The only difference is inbetween past and future desktop UIs lies GNOME 3. GNOME 3 will pave the way for future desktop UIs. I am using computers from last 10 years and WMs from last 5 years and in last 3 years I tried to use different desktops but could never use any for more than 2 minutes. Now I am using GNOME 3 from 2 weeks because GNOME 3 is not just a desktop, it is the reincarnation of desktop. I see that desktop is moving from traditional way (eye-candy) towards more usable way (tiling WMs) and GNOME 3 team has shown us the way. GNOME 3 team is decade ahead in innovation, is solving practical problems and I think it needs a well-done pat-on-the-back from me at least for their great work
Copyright © 2013 Arnuld Uttre, Village – Patti, P.O – Manakpur, Tehsil – Nangal, Distt. – Ropar, Punjab (INDIA). Image produced above is a modified work of art (originally taken from Wikipedia) and hence released under the license mentioned at http://en.wikipedia.org/wiki/Thumbs_signal
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.
C++ new() operator
June 28, 2012 at 7:17 pm | Posted in C++, Programming | Leave a commentTags: C language, C++, programmer, Programming
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.
Project Euler – Problem 2
June 11, 2012 at 10:14 am | Posted in Programming | Leave a commentTags: Project Euler, project euler solutions
I mentioned Project Euler in my previous post. Next problem was little bit hard to do and I rewrote my code 3 times before I got it right:
/* By considering the terms in the Fibonacci sequence whose values do not exceed four million,
* find the sum of the even-valued terms.
*/
#include <stdio.h>
unsigned long fib(unsigned long num);
int main(void)
{
const unsigned long limit = 8;
unsigned long sum = 0;
unsigned long i = 0;
for(i = 0; i <= limit; ++i)
{
unsigned long j = fib(i);
if(0 == (j % 2))
{
sum += j;
}
}
printf("Sum of all Fibonaci even numbers upto %lu = (%lu)\n", limit, sum);
return 0;
}
unsigned long fib(unsigned long num)
{
unsigned long temp = 0;
if((0 == num) || (1 == num))
{
temp = 1;
}
else
{
temp = fib(num - 1) + fib(num - 2);
}
return temp;
}
What can you see from above code. I got the meaning of problem statement totally wrong. Problem says “I need to add all Fibonacci numbers with values upto 4 million” whereas I took it as “add all numbers upto 4 million as input to Fibonacci”. 2nd, What else is wrong ? Can you spot it ? Stop reading right now and run this in your compiler. If you have gcc then please use -ansi -pedantic -Wall -Wextra flags. Go ahead and try and come back again. This program keeps on running for 11 minutes when limit is 400. The recirsive call eats all CPU. Even after 11 minutes I killed it. My machine is quite average in terms of hardware. Imagine at 4 million as input, how many years it will take to complete ? So what do we do ? First we get our brains right that it requires us to add all Fibonacci values less than 4 millions. 2nd, we will not use recursion and instead we will make use of the fact that F(N) = F(N-1) + F(N-2) provided F(0) = F(1) = 1, where F is fibonacci for N. We can rememeber last two fibonacci numbers in some variables instead of using recursion to find out every time. Recursion uses a lot of stack and I don’t think you should assume that you will have stack for 4 millions. Here is the correct and new iterative version.
/* By considering the terms in the Fibonacci sequence whose values do not exceed four million,
* find the sum of the even-valued terms.
*/
#include <stdio.h>
int main(void)
{
const unsigned long limit = 4000000;
unsigned long sum = 0;
unsigned long i = 0;
unsigned long f = 1; /* Fibonacci(0); */
unsigned long f2 = 1; /* Fibonacci(0); */
unsigned long f1 = 1; /* Fibonacci(1); */
for(i = 2; f <= limit ; ++i)
{
/* In first iteration, Fibonacci(2) = F(1) + F(0) */
f = f1 + f2;
if(0 == (f % 2))
{
sum += f;
}
f2 = f1;
f1 = f;
}
printf("Sum of all Fibonaci even numbers upto %lu = (%lu)\n", limit, sum);
return 0;
}
I still see something wrong with above code. Did you notice several issues ? Don’t just read ahead, read the code and see how it fits problem statement. Its using <= instead of < . Problem statement says “upto 4 millions” and that does not include 4 millionth term (##c on freenode correct me on this as I am not a native English speaker. I thought “upto” included 4 millions). Other problem is using iteger i. We are not iterating for a specific number of times but till a certain condition is reached without caring how many times we iterated. So we need to remove that counter.
/* By considering the terms in the Fibonacci sequence whose values do not exceed four million,
* find the sum of the even-valued terms.
*
* My Method: F(n) = F(n-1) + F(n - 2) (where F(0) = F(1) = 1)
* find the sum of all values where F(n) is even, till 4 million
*
*/
#include <stdio.h>
int main(void)
{
const unsigned long limit = 4000000;
unsigned long sum = 0;
unsigned long f = 0; /* Fibonacci(0); */
unsigned long f2 = 0; /* Fibonacci(0); */
unsigned long f1 = 1; /* Fibonacci(1); */
while((f1 < limit) && (f2 < limit))
{
/* In first iteration, F(2) = F(1) + F(0) */
f = f1 + f2;
if(f >= limit) break;
if(0 == (f % 2))
{
sum += f;
}
f2 = f1;
f1 = f;
}
printf("Sum of all Fibonaci even numbers upto %lu = (%lu)\n", limit, sum);
return 0;
}
How long it takes to execute. As per ideone.com , it take 0.02 seconds. And I was waiting for 11 minutes for the first piece of code. How much good programming practice is worth of ? a few thousands extra in salary of the programmer, a millions for the bugs caused or the entire bank account multi-billioon dollor corporation if it hires all bad programmers ? What do you think ?
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 commentTags: coding horror, f5 essential phone interview questions, Five Essential Phone-Screen Questions, steve yegge
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 solved only several questions, will solve others when I get time to sit on machine next time. For now, just 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 <stdio.h>
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 <= 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 <= limit; i = i + 2)
{
printf("%d\t", i);
}
printf("\n");
}
void print_fizzbuzz(const int limit)
{
int i;
for(i = 0; i <= limit; ++i)
{
if((0 == i%3) && (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.
Blog at WordPress.com. | Theme: Pool by Borja Fernandez.
Entries and comments feeds.
