# How does malloc(sizeof(char)) work [closed]

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?

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

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