c - strncpy implementation too complicated in glibc -
i'm trying understand string.h functions. here own implementation of strncpy()
char * my_strncpy(char *dst, const char* src, int n) { char *orig = dst; const char *hold = src; int count = 0, remain = 0; while(*(hold++)) count++; if ( n > count ) { remain = n - count; n = count; } while(n--) *dst++ = *src++; while(remain--) *dst++ = '\0'; homecoming orig; } but while looking @ glibc implementation here, i'm wondering why big , complicated.
i tested execution time using "time" command. both functions run same. can share knowledge on glibc strncpy() , i'm missing in my_strncpy().
from modern c programming perspective, "glibc" code badly written. looks collection of premature optimizations 1 particular platform 32 bit alignment. if compiler crap, you'll have grouping bytes in units of preferred alignment , re-create them 1 such unit @ time. that's main reason why code looks weird.
i guess code written long time ago, when compilers lot worse @ optimizing code , cpus had less hardware back upwards things these. inconsistent, seemingly random way switch , forth between prefix postfix increment suggests code written poor compiler.
apart pre-mature optimization, code finish spaghetti, there no sensible explanation for. finish lack of comments suggests code written bad programmer.
so sum up, there may or may not various historical reasons why wrote code in way, there lots of bad programming practice in code can't dismissed pre-mature optimizations.
just dismiss code rubbish.
also please note strncpy function obsolete , should avoided. strncpy meant used ancient string format in unix. it never intended safe version of strcpy. on contrary, function unsafe , known cause lots of bugs because of accidental missing null terminations.
the standard specification of strncpy forces lot of pointless things, checking null termination when know length in advance. also, 1 may wonder fill remaining characters after first \0 more \0. of these pointless requirements create function needlessly slow.
so there never reason utilize strncpy anywhere in modern c code. proper way re-create strings of known length this:
memcpy(str1, str2, str2len + 1); c glibc strncpy
No comments:
Post a Comment