Monday, August 15, 2011

Civilized Programming Language

Code worked and stopped working after minor changes. All of the sudden a loop is not working anymore.

1 while(cursor != NULL)
2 {
3 printk("mock_config_cache: checking %x\n", cursor);
4 if (mock_compare_cache_devices((mock_cache_device_t*)cursor, new_cdev))
5 {
6 printk("mock_config_cache: Device already exists: %x\n", cursor);
7 status = IOCMD_ERR_DEV_EXISTS;
8 mock_free(new_cdev);
9 break;
10 }
11
12 cursor = cursor->next;
13
14 if (cursor == cache_devices);
15 {
16 break;
17 }
18 }
19





It should be easy, but this is a kernel code, so I’ve spent 1.5 hours to debug this code. Even if it weren’t a kernel code, it is not always easy to attach a debugger and step through the code. I’ve added a loop to print the linked list, which is basically the same code:



1 /* DEB */
2 cursor = cache_devices;
3 while(cursor != NULL)
4 {
5 printk("Cursor: (%x), next: (%x), prev: (%x)\n", cursor, cursor->next, cursor->prev);
6 cursor = cursor->next;
7 if (cursor == cache_devices)
8 break;
9 }
10





The same code, but this one is working!


Another coffee and I see the bug. Line #13 in the first code:


1 if (cursor == cache_devices);


Notice the “;” at the end of the line! DAMN! This is frustrating!



Now, the compiler should have told me something, as the IF statement does not even have a side-effects!



These days I have read an article by Andrei Alexandrescu (C++ template guru) called: “The case for D”, where he praised D language as a better C/C++. Naturally, I wondered if D would do better in the above bug:



1 import std.stdio;
2
3 void main()
4 {
5 writeln("hello world");
6
7 int i=3;
8 if (i == 3);
9 {
10 writeln("another hello");
11 }
12 }





OK. Let’s see:




C:\Users\derbep\Documents\Code\DTest>dmd if_test.d




if_test.d(8): use '{ }' for an empty statement, not a ';'







Much much better! Advance to D! It is better!

No comments: