c - Can I copy a string in an empty string? -


suppose copy string.

char str[] = ""; char *str2 = "abc"; strcpy(str, str2); printf("%s", str);  // "abc" printf("%d", strlen(str));  // 3 

then, why doesn't give me undefined behaviour or causing program fail. disadvantages of doing ?

this code causing stack problem, though such small string, not seeing issue. take, example, following:

#include <stdio.h> #include <stdlib.h> #include <string.h>  int main() {         char str[] = "";         char *str2 = "a really, really, really, really, really, loooooooooooooooonnnnnnnnnnnnnnnnng string.";         strcpy(str, str2);         printf("%s\n", str);         printf("%d\n", strlen(str));         return 0; } 

a contrived example, yes, result of running is:

a really, really, really, really, really, loooooooooooooooonnnnnnnnnnnnnnnnng string. 92 segmentation fault 

this 1 of reasons why strcpy function discouraged, , usage of copy , concatenate functions require specifying sizes of strings involved recommended.


Comments