The following code outputs "test". Shouldn't it print "te" only, since there are only two bytes allocated for x?
char *x = malloc(sizeof(char)*2);
x = "test";
printf("%s",x);
How does strcopy do this job correctly?
The following code outputs "test". Shouldn't it print "te" only, since there are only two bytes allocated for x?
char *x = malloc(sizeof(char)*2);
x = "test";
printf("%s",x);
How does strcopy do this job correctly?
Actually, if you print the value of x before and after calling:
x = "test";
You will see that it has changed. By losing a track to your allocated memory, you face with memory leak here.
Furthermore, printf prints a string that starts from the pointer position until it finds the string terminated '\0' (0).
Suggested solution:
char* x = malloc(5); /* sizeof(char) is always equal to 1 */
strcpy(x, "test");