c - How strcpy works behind the scenes? -
c - How strcpy works behind the scenes? -
this may basic question some. trying understand how strcpy works behind scenes. example, in code
#include <stdio.h> #include <string.h> int main () { char s[6] = "hello"; char a[20] = "world isnsadsdas"; strcpy(s,a); printf("%s\n",s); printf("%d\n", sizeof(s)); homecoming 0; }
as declaring s
static array size less of source. thought wont print whole word, did print world isnsadsdas
.. so, thought strcpy function might allocating new size if destination less source. now, when check sizeof(s), still 6, printing out more that. hows working actually?
you've caused undefined behaviour, can happen. in case, you're getting lucky , it's not crashing, shouldn't rely on happening. here's simplified strcpy
implementation (but it's not far off many real ones):
char *strcpy(char *d, const char *s) { char *saved = d; while (*s) { *d++ = *s++; } *d = 0; homecoming saved; }
sizeof
returning size of array compile time. if utilize strlen
, think you'll see expect. mentioned above, relying on undefined behaviour bad idea.
c pointers
Comments
Post a Comment