Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Do we have a source for what the intended purpose is? I think you speak well to the effective purpose, but I'm not sure if it was that clear when it was introduced.


> I think you speak well to the effective purpose, but I'm not sure if it was that clear when it was introduced.

It was completely clear, and can easily be inferred from its specified behaviour.

It's just completely useless nowadays, because its purpose is essentially obsolete, because the data type it works with is almost never used anymore.

strncpy works with fixed-size nul-padded fields as you'd find in e.g. mainframe-type software. That is why it:

- fills the destination buffer with NULs if the source is shorter

- does not nul-terminate if the source is the same size or longer than the destination

strncpy is essentially equivalent to zero-ing a buffer of size `n` then copying the first `n` bytes of src (up to the first nul) in the target


That's your understanding now. Fine, but not evidence of what someone else thought about this some decades ago.

(I don't use strncpy and don't defend its functionality, just want to know what was intended when it was introduced.)


I found an actual quote of a source which verifies the intention for fixed-length fields: https://softwareengineering.stackexchange.com/a/438090


On early Unix systems, the directory structure was a simple 16-byte record; 14 bytes for the name, and 2 bytes for the inode. [1] strncpy() was used to simply record the file name into this structure.

[1] "UNIX Implementation" by Ken Thompson, _The Bell System Technical Journal_, July-August 1978, Vol 57, No 6, Part 2, pg 1942.


Many protocols still relevant today make use of that structure, it still has widespread use.


For the average protocol you're going to init the entire message then set into it, you don't need to fully zero fields.

This is mostly relevant to write into existing memory or memory-mapped records.


Sometimes yes, but you must also not null-terminate the strings in those cases.

And on embedded devices you are often memory constrained so you might reuse an existing structure.



Doesn't say anything about the intention as understood when it was introduced




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: