AFAIK, malloc(sizeof(char)) is intended to allocate a 1-byte block of VM and strcpy requires that

the destination string dest must be large enough to receive the copy

That means theorically that if the length of src is strictly upper to 1, the strcpy operation fails, and it's impossible to copy more than one character to src.

However, the following code shows a counterexample, where 27 characters gets copied to s (including the '\0') as the program displays:

s length = 26

  char *s = malloc(sizeof(char));

  strcpy(s, msg);

  printf("%s\n", s);
  printf("s length = %i\n", strlen(s));
  printf("msg length = %i\n", strlen(msg));

So, why malloc(sizeof(char)) allocates 27 characters contrarily to what it is intended to allocate theorically? How does this allocation work?

  • $\begingroup$ Questions about programming are off topic here. StackOverflow is the proper site to ask those. $\endgroup$
    – chi
    May 13, 2017 at 15:53
  • 2
    $\begingroup$ That requirement does not say that it will stop you from violating it, it puts the burden on you to satisfy it. $\endgroup$
    – harold
    May 13, 2017 at 17:30

1 Answer 1


Quick note, sizeof(char) is defined to be 1. So you can just simplify to malloc(1).

The real answer however is quite boring. Your program has what's so called undefined behavior. In C (and C++), if you make an error like this the result is undefined. This could mean that your program will crash right as you trigger the bug. But it doesn't necessarily crash. It might do what you expect. It might format your hard drive and kill your cat. Whatever happens is fair game according to the C standard. Because you triggered undefined behavior.

  • $\begingroup$ So does the execution result depend on the OS mmu, then? $\endgroup$ May 13, 2017 at 17:48
  • $\begingroup$ @user6039980 The result is undefined, for all I care it could depend on the position of the moon. $\endgroup$
    – orlp
    May 13, 2017 at 17:56
  • 1
    $\begingroup$ @user6039980: The C Language Standard doesn't mention "OS" and it doesn't mention "mmu", so they will be quite irrelevant. As a mental model, use "anything can happen, and whatever happens will cause maximum damage". $\endgroup$
    – gnasher729
    May 14, 2017 at 19:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.