3 ms·
One-liner summary: Author suggests using just memcpy() typically, strncpy() rarely/maybe, and even more rarely, or never, strcpy().
by einpoklum 5y ago
One-liner summary: Author suggests using just memcpy() typically, strncpy() rarely/maybe, and even more rarely, or never, strcpy().
- ajanuary 5y agoI don’t think that’s an accurate summary. “Use memcpy() instead. Use strncpy() in limited circumstances.”
- icedchai 5y agoDoesn't memcpy have the same issue as strncpy? the destination will not be null terminated if the source is too long. Many projects just implement a safe_strncpy wrapper that always terminates the destination. Example: https://github.com/brgl/busybox/blob/master/libbb/safe_strncpy.c https://github.com/brgl/busybox/blob/master/libbb/safe_strnc...
- typical182 5y agoI think though it is recommending against strncpy as well… linters and code reviewers commonly recommend alternatives such as strncpy (difficult to use correctly; mismatched semantics) […] Besides their individual shortcomings, these answers are incorrect. strcpy and friends are, at best, incredibly niche, and the correct replacement is memcpy.
- tialaramex 5y agostrncpy() does a specific thing really well. If it's the 1970s where you are and you're writing Unix filesystem code or some 1970s data processing application your program likely has a use for strncpy() and it matches the semantics you need exactly. But it isn't intended as a solution for buffer overflow bugs in your program, and so if you try to abuse it to solve that problem you likely introduce more problems. Imagine your car's air conditioning doesn't work properly. On sunny days it's really much too hot in the car. So, you buy a sunroof. Says "Sun" right in the name, surely that will help right? No. That's not what a sunroof is for. The sunroof works fine as a sunroof but that is not what you needed.