logoalt Hacker News

Someoneyesterday at 5:40 PM3 repliesview on HN

> I've always wondered at the motivatons of the various string routines in C

This idiom:

    char hostname[20];
    ...
    strncpy( hostname, input, 20 );
    hostname[19]=0;
exists because strncpy was invented for copying file names that got stored in 14-byte arrays, zero terminated only if space permitted (https://stackoverflow.com/a/1454071)

Replies

masklinnyesterday at 6:03 PM

Technically strncpy was invented to interact with null-padded fixed-size strings in general. We’ve mostly (though not entirely) moved away from them but fixed-size strings used to be very common. You can see them all over old file formats still.

BobbyTables2yesterday at 11:39 PM

It’s also horrible because each project ends up reinventing their own abstractions or solutions for dealing with common things.

Destroys a lot of opportunity for code reuse / integration. Especially within a company.

Alternatively their code base remains a steaming pile of crap riddled with vulnerabilities.

show 1 reply
messetoday at 10:15 AM

I've always assumed that the n in strncpy was meant to signify a max length N. Now I'm wondering if it might have stood for NUL padding.