what are the most common bugs in your D apps?

bearophile bearophileHUGS at lycos.com
Sun Apr 12 06:28:42 PDT 2009


The following one isn't a problem of D, it's a small bug I've created while translating C code to D.
Here I have reduced the code to a very small proggy, so you probably need only a moment to spot the problem.
This program takes a string that contains more than one natural numbers, and returns their sum.
Example:
200+350 => 550

The original C code:

#include <stdio.h>

int main() {
    char* numbers = "200 350";

    int total = 0;
    char* p = &numbers[0];
    int cur = 0;

    while (*p != 0) {
        char c = (*p) - 48;
        if (c >= 0) {
            cur = (cur * 10) + c;
        } else {
            total += cur;
            cur = 0;
        }
        p++;
    }
    total += cur;

    printf("total: %d\n", total);
    return 0;
}


The D code is exactly the same, but it contains a bug:

import std.stdio: printf;

int main() {
    char* numbers = "200 350";

    int total = 0;
    char* p = &numbers[0];
    int cur = 0;

    while (*p != 0) {
        char c = (*p) - 48;
        if (c >= 0) {
            cur = (cur * 10) + c;
        } else {
            total += cur;
            cur = 0;
        }
        p++;
    }
    total += cur;

    printf("total: %d\n", total);
    return 0;
}

A C programmer probably needs 5 seconds to spot the bug.
There is a standard way for a compiler to avoid such bugs.
Later I may paste here another bug created from porting C code to D.
I think a FAQ can be created to list such most common troubles.

Bye,
bearophile



More information about the Digitalmars-d mailing list