Hacker News new | past | comments | ask | show | jobs | submit login

With memcpy() you need to know the exact length, i.e. it needs to be kept around and passed to the point of the copy. With strcpy(), once you have determined that a string will always be below a maximum length, it is no longer necessary to retain its exact length until if/when it is actually needed by a copy.



In 2022, having 4 bytes to store the length of the string (or even 8 if you want to be fancy) is not onerous.

Like all things, never say "for all" or "always" but almost all strings can be buffers packed with a size in a struct like in the top comment.


> never say "for all" or "always"

The 4KB of RAM in my microcontroller would appreciate those extra 4 bytes (or 3) used for every string.


If you use a microcontroller with 4kb of ram you should know the length of all buffers you use so you don't need to store it. For NES programming, which has 2kb you don't program C at all...much less wasting cycles doing things like strlen. It's tedious but rom is bigger and you can "store" the length of things in the instruction themselves (ie., hardcoded lengths), whereas ram is saved for more important things like position of sprites or whatever.

I really hope people aren't seriously doing string parsing on microcontrollers.


But I thought we were talking about compilers here, and defining what a compiler should do when it comes across a string literal, and not about what people should or shouldn’t do with strings on 4KB RAM MCUs.

String parsing is sometimes necessary, and it could be as simple as formatting and sending logs lines through an UART.


Why you need 4 bytes of length when you have 4Kb of RAM? 1 byte should be enough for you.


If the 4 bytes are reserved by the C compiler then there isn’t much to do (unless there is a flag to control bytes for strings length).

One byte is the actual overhead for strings.


4KB of RAM doesn’t mean only 4KB of addressable space. (Even if it was, you’d expect a 16b size_t.)




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

Search: