Contra char *argv[]

Language warning.

Linus Torvalds hits the nail on the head in this message from the Linux kernel mailing list (September 2015). He’s talking about a buggy refactoring (made here, fixed here) which essentially refactored

void test() {
    char mcs_mask[IEEE80211_HT_MCS_MASK_LEN];
    for (int i=0; i < sizeof(mcs_mask); ++i) {  // sketchy but correct
        mcs_mask[i] &= SOME_MASK;
    }
}

into

void helper(char mcs_mask[IEEE80211_HT_MCS_MASK_LEN]) {
    for (int i=0; i < sizeof(mcs_mask); ++i) {  // totally wrong
        mcs_mask[i] &= SOME_MASK;
    }
}

void test() {
    char mcs_mask[IEEE80211_HT_MCS_MASK_LEN];
    helper(mcs_mask);
}

Linus writes:

I [really] want people to take a really hard look at functions that use arrays as arguments. It really is very misleading, even if it can look “prettier”, and some people will argue that it’s “documentation” about how the pointer is a particular size. But it’s neither. It’s basically just lying about what is going on, and the only thing it documents is “I don’t know how to C”. Misleading documentation isn’t documentation, it’s a mistake.

Please, don’t use [] syntax to declare pointers.


Previously on this blog:

Posted 2020-03-12