Wednesday, December 1, 2010

goto vs return statement: C programming

It is a classic conflict of opinion when comes to choosing between goto and return.

I feel that goto is treated unfairly, biased, and unjustly. Why people are so paranoid about avoiding goto, is beyond my comprehension.

Let me explain my point with following example:

void foo()

Now if I populate the body of "if" with "return"; it is perfectly okay. It creates problems in later point of time.

Now, say you allocate a resource in foo(), where would you free it?

Going with "return" makes you free the resource in all "if" conditions that follow the place where you have allocated the reosurce.

Now, solve this problem with goto. All "if" should goto a single label, which would be placed at the end of the foo().

So, the clean-up work can now be placed under this label. This is much better than "return" statements:

- Code is more exensible. You may add more "if" conditions, without any fear of resource leaks.

- Avoids code duplication

- Even if the current function do not need "goto", I propose to use "goto" for future extensibility.

Saturday, November 13, 2010

The best virtualization software: VirtualBox v/s VMPlayer

I was an avid user of VirtualBox and was pretty happy with it. It gave me freedom to experiment with different OS in a rather safe, transparent, and convenient way. So I used to keep Linux as host and Windows as guest. Performance was good and bugs were non-existent.

Then I found VMPlayer. It surprised me a lot with following reasons:

a) It supported ISO images for Ubuntu, my fav Linux disto.

b) Set up was easier/comparable to VirtualBox.

c) Unity mode: What a feature! A seemless integration of guest OS with host application. You don't have to click the mouse, you never lose window focus. I can now browse through guest OS with Alt+Tab.

d) Very stable, good performance, and I am a happy customer.

Wednesday, October 20, 2010

How tail -f work?

"tail -f" is a special command in a way that it polls the specified file for any change and prints the new stuff on the fly. It is very helpful in observing logs and any event based data.

Ever wondered how tail achieves this?

"tail" opens the given file and obtains the file-descriptor. It opens it with xfreopen() -> freopen() -> fopen() call. It does its first round of fstat() on the file as well.

Once it has got the fd, it loops infinitely and do the following:

It does fstat() of the file and observes the mtime value. If the mtime value is changes from the last dumps the data. To print the latest data, it lseek() the file to the last reported file size.


Sunday, September 19, 2010

How touchpad of a laptop work?

It was a curiosity to know the internal details of one of the most used 6x6 cm2 part of a laptop. My curiosity increased with diffrent behavior of the touchpad with different objects. For example, it works well with fingers but a pen, pin, or paper are not entertained.

So how does it work?

It is based on concept of capacitive difference on two parallel plates. Each of these plates have a grid of conductors. When we put our finger on the surface, it creates a charge difference on this surface and the difference of capacitance is sensed by the hardware.

This difference is mapped to mouse motion on our screen.

Thursday, September 16, 2010

MeeGo: Marriage of Nokia and Intel

Nokia and Intel are merging their Linux based intiatives: Meamo and Moblin = Meego

* Open source platform to serve mobiles, notebook, TV, and tablets.
* Hosted under Linux Foundation
* Support x86 and ARM
* Visit for more information

But why would people use this new OS? What's wrong with Andriod? How is it better than Symbion, Android, Windows Mobile or BADA?

We already have Linux based mobile OS, so it'd be hard for this new guy to find a decent place.

Monday, September 6, 2010

Uninterrupted Linux session : screen command

Have you ever faced losing connections to a remote machine(e.g. from a putty) and you happened to be in middle of a script that took ten hours to complete. So what would you do??

Restart the script after re-connecting.

Not anymore...

Linux screen solves this problem with providing a terminal that runs on server and just exported to your putty/Terminal client. In simple terms, you are running your putty on remote machine and watching the output on your local client.

Now, if you client goes down, just chill!

Screen is running your script on remote machine.

To start a screen session:
- Login to remote machine with as you may wish.
- Run $screen
- Do you stuff

Power cut and, no net connection and your client is down.

Once power is back, just re-login to remote machine.
and issue:
$screen -r

It'll list all screen sessions running on the remote machine. Get attached to one of the session with:

$session -r


Saturday, August 21, 2010

Expect Pexpect: Python module to help you automate interactive tests

Many a times we encounter writing a code that requires user input to proceed. Testing and validating such an application can become tedious and frustating. Python implements an elegant solution to cut down the effort needed to "talk to application".

This is called pexpect module, borrowed from Tcl "expect". Pexpect is a tool for controlling and automoating programs. It simple "fools" the application with an user input. It runs the program and monitors the output. When output matches a given pattern, it respond to application mimicking the human intervention.

Pexpect can be extensively used in testing and automation. I found it particularly useful for interacting with application like ssh, ftp, passwd, telnet etc.

It comes packaged with standard Ubuntu 9.10. The version of Python used by me is:

$python --version
Python 2.6.4rc2

Saturday, July 31, 2010

Half century of technical know-how sharing

It's 50th post on this blog. I am happy with my contribution. Learning is a continuous process and I am an active participant. Today's post will talk of something that I had never imagined to do in my development career: Testing.

Testing of the product is an interesting job, especially when you are a new user. Past two weeks, I am testing the product I'd be developing.

I'm sharing my experience here:

- Don't test just for sake of doing it; Understand the ecosystem in which your product would be working.
- Take generous logs of your testing.
- Keep an eye on what you can improve: Be it a process or a feature.
- Try to automate processes if possible.
- Try feeding weird input to your product.
- Testing is learning. You become a very good user of your product.

Friday, June 18, 2010

Bash Command fo you

Once again, I am sharing a few good commands with you.

a) Run command in a subshell
$(cd /tmp && ls)

# You will see the contents of /tmp but will stay in PWD only.

b) Reusing cscope database
$cscope -d

c) If you default shell is csh, and you want to move to bash as soon as you login
- Create a file .cshrc in your home directory.
- Edit and add "bash"
- Save and exit.

d) vi can help you see a split screen with two or more files. Try :vsplit.

Wednesday, May 19, 2010

Ubuntu 9.10 on Windows XP: Virtual Box

My office laptop has Windows XP installed and I need Windows for sake of Outlook and Communicator. So I started to look out for alternative for having Linux on my laptop. There were three options suggested by different people:

- Get Ubuntu installed and run Windows XP as a guest on VirtualBox.
Now my workplace's IT guys do not install Windows on a VM, so they asked me to create an image of the Windows installed on my laptop. I searched for software to accomplish this and tried a few in vain. I tried a software called WinDD to copy Windows image to my portable HDD and since I did not checked thoroughly where it was copying, I got my portable HDD corrupted. It caused me a lot of pain, my important docs and many pics just got shredded.
Well that was it. I dropped this option.

- Get the Ubuntu on a pen-drive(PD) and make your PD boot-able.
It had a problem that Ubuntu installation was not persistent. Many of my setting could not be saved. Though I got a way to create a persistent image, still it can't save a few things like system time. Verdict: Dropped

- Get the Ubuntu running as a guest on host Windows.
After installing the guest additions, I am very happy with the screen resolution. I got few glitches with network setting and shared folders help. I got over them and will post the details in the next post.

So I am a happy man now, seeing my Ubuntu running on XP. All happy and gay!

PS: I am a fan of VirtualBox and so far have not used any other VM software.

Monday, April 26, 2010

Torrent: Demystified

What is a torrent?

A torrent is like a broker between a customer and a seller. It works in a peer-to-peer setup that means a true democracy; all are equal, no master-no slave.

So you need to download a classic movie, which may be on a computer(s), located anywhere across the globe.

How would you know where is it?

Torrent comes to help you here. You google for a torrent of this movie. Download the torrent and voila!.

Torrent has three primary components:

a) Seeders: People that have a copy of the movie you want
b) Leechers: That's you!
c) Torrent file : It has information about seeders and leechers.

While you are downloading your movie, torrent share the downloaded part with anyone else interested in downloading the same movie. So effectively every leecher becomes a seeder. Now you are even! Hail Democracy!!

Sunday, April 11, 2010

Ubuntu 9.10: Wireless network problem with Broadcom Corporation BCM4312

Many laptops with Broadcom Corporation BCM4312 802.11b/g hardware shows no response to wireless network with Ubuntu 9.10 Casper.

I could solve this problem with the following method:

a) Go to System-> Administration->Hardware Drivers
Keep your system on Internet(wired ethernet) while doing this.

Install Broadcom 43 and Broadcom STA driver, activate them then.

b) Reboot and see if it work for you.

c) If not, then do the following:

sudo apt-get --purge remove bcmwl-kernel-source
sudo apt-get install patch
sudo apt-get install bcmwl-kernel-source

This should solve the matter. At least it worked for me :)

Ref: Ubuntu Forum

Wednesday, April 7, 2010

Running Ubuntu 9.10 Casper On your PC

A complete solution: Image Writing to Installation

Ubuntu is a free open source Linux distribution, primarily for desktop users. There are many reasons to use Ubuntu instead of other Linux distro(Just Google for it).

I am assuming that reader is an Ubuntu user on a x86 system and knows some stuff about Linux.

o) First thing is get the latest Ubuntu bundle(an .iso file) from Ubuntu website.
o) Now get a pen drive.
o) From "Application" menu, run USB creator.
Give the path of iso file and click create USB drive.
+ If pendrive is more than 4GB, You would get an error saying "partition not found":
Just do the following:
* Install gparted utility with Synopsis Bundle Manger
* Create a partition table with "gparted" on your pendrive
* Now create a FAT32 partition of size 1000MB on this pendrive
o) Run USB startup disk creator again.

o) Voila! You are done

o) You save money spent on CD/DVD to write Ubuntu image.
o) This method is very fast and reliable, compared to use of optical media.

Thursday, March 25, 2010

Thread stack in heap (pthreads)

I had known that a thread has a stack. But never thought where is this stack lie in the memory?

Well, it should be process stack. But you can set the thread stack to a heap area.

How to do that?

#include "pthread.h"
#include "stdio.h"
#include "unistd.h"

pthread_mutex_t mutex1;

void* foo(void *arg)
int arr[1024*8];

int x = 0;
while(x++ < (8*1024) )
{ arr[x] = x; }

puts("Thread created");

int main()
int *p;
void *ret;

p = malloc(1024);


pthread_attr_t attr;

pthread_attr_setstack(&attr, p, 2);

pthread_t thread1;

pthread_create(&thread1, NULL, foo, NULL);

pthread_join(thread1, &ret);


return 0;

But still I am not very sure of this concept.

Stay tuned for more!

Monday, March 22, 2010

Some thoughts on Linux malloc()

* Always check for equal number of malloc()/free() calls.
• Use calloc() instead of malloc() + memset()
• Instead of allocation memory in a piece-meal manner, try to allocate a bigger chunk with malloc() and keep on resizing it with realloc() if needed.
• malloc() over-commits the memory i.e. it gives you an address which actually does not exist!
• malloc() grouping & reallocing with "more than you want"

Thursday, March 11, 2010

Cut short your web-addresses: TinyURL

An utility called "tinyurl" makes your life easier with shorter URL without creating an all new website. Many times it become cumbersome(i.e. for a long string) and unsafe(if you miss to copy contents of the link) to send a link to your friend.

TinyURl helps you with providing an alias for a long link. Concept is very simple but effective.
e.g. a link is: "http://"

You may get an easier name for this link as:

Here is more information this:

Saturday, February 20, 2010

Exceptional exception handling in C++


using namespace std;

int a = 20;

void foo()
try {
throw a;
catch(int &x)
// You can't modify value of "a"
x = 10;

int main()
cout<<"A="< }

A=20 !!!!
When you write "throw a", an invisible, phantom exception object gets created. You pass reference to that object and hence any change made to original object have no effect.

Friday, February 19, 2010

Mutex v/s Semaphore v/s Spinlock


- All are used for synchronization


Mutex provides one person to access a resource at a time, others must wait in a queue. Once person is done, the guy next in the queue acquire the resource.
So access is serial, one guy after other.

Semaphore provides more than one(up to N) guys to access N resources. So it gives you parallel access to a resource.

Spinlock is an aggressive mutex. In mutex, if you find that resource is locked by someone else, you (the thread/process) switch the context and start to wait(non-blocking).
Whereas spinlocks do not switch context and as soon as resource is free, they go and grab it. In this process of spinning, they consume many CPU cycles. Also, on a uni-processor machine they are useless and perform very badly (do I need to explain that?).

Thursday, February 4, 2010

GL: Question

- fun(int, int);
fun(char, char)
Are they overloaded properly?

- Using static variable in a member function?

- Finding the common node of two link lists?

- Implement BFS, DFS?

- Inorder, preorder is DFS or BFS?

- What is a heap?

- Deleting a node in BST?

- Difference of memcpy() and strcpy()

Wednesday, January 6, 2010

C Structures: Calculating offset of an element

Let's say we have the following structure:

int a;
char c;
} example;

To calculate offset of 'c', we have following ways:

1. Use the macro offsetof() defined in header file stddef.h.
unsigned int x = offsetof(struct example, c);
This macro takes care of padding of elements done by the compiler.

2. Other way to get the offset f c is:
// C snippet
example var, example *ptr;
ptr = &var;
offset = &(ptr->c)- &(ptr->a)

------|base_addr = 0x0000
int a |
------|addr = (0x0000 + 0x0004)
int c |
------|addr = (0x0004 + 0x0004)

We are getting the distance of 'c' from base of the structure. So, address &(ptr->c) should be calcuated by compile as: base_address of var + distance of 'c' from base
If we somehow set base_addr as zero, we will get the offset i.e. 0x0004.

A hack to accomplish this result is as follows:
#define POINTER = ((struct example*)(0))
unsigned int x = (unsigned int) & (POINTER->c);

We are typecasting an address '0' pointing to a type of data 'struct example'.
Now when you do (x)->c, it is equivalent to: BASE_ADDESS(x) + size_of_data elements preceding 'c'. We are tricking the compiler by giving BASE_ADDRESS as zero.

This hack may be incorrect if element padding is done by the compiler.