1
$\begingroup$

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

int
main()
{
  const char *msg = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
  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?

$\endgroup$

closed as off-topic by chi, David Richerby, D.W. May 14 '17 at 1:42

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions about software development or programming tools are off-topic here, but can be asked on Stack Overflow." – chi, David Richerby, D.W.
If this question can be reworded to fit the rules in the help center, please edit the question.

  • $\begingroup$ Questions about programming are off topic here. StackOverflow is the proper site to ask those. $\endgroup$ – chi May 13 '17 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 '17 at 17:30
3
$\begingroup$

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.

$\endgroup$
  • $\begingroup$ So does the execution result depend on the OS mmu, then? $\endgroup$ – Kais May 13 '17 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 '17 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 '17 at 19:12

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