-6

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?

damat-perdigannat
  • 5,780
  • 1
  • 17
  • 33
  • 3
    You aren't doing what you think you are.... You are reassigning x to point to a different constant string and leaking the memory you allocated. – JohnH Jul 22 '14 at 02:35
  • That doesn't look like a duplicate, the OP here is assigning `x` a new value, not copying the content. – Yu Hao Jul 22 '14 at 02:36
  • @JohnH would it still be the case if I use x= "te"; ? – damat-perdigannat Jul 22 '14 at 02:37
  • Yes, it is a leak for the same reason. – JohnH Jul 22 '14 at 02:38
  • @JohnH how can I let the allocated two bytes contain the characters "te" then? – damat-perdigannat Jul 22 '14 at 02:40
  • 1
    Read the link that @user93353 posted. It shows how to do that, and explains the consequences. – JohnH Jul 22 '14 at 02:41
  • 1
    @user33856: `memcpy` or `strcpy`. Read a basic C tutorial… And if you changed your assignment to `strcpy(c, "test")`, you'd probably get the same result, but have undefined behavior. In C, you cannot determine if some code is valid by just compiling and running it… – mafso Jul 22 '14 at 02:44

1 Answers1

0

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");
Long_GM
  • 181
  • 1
  • 10