Please take a look at this piece of code. I’m allocating one byte for the first variable and another byte for the second one. However, it seems like the compiler allocates more (or I’m missing something). The program outputs both strings, even though their length is more the one byte.
void main() {
char* some1 = malloc(1);
sprintf(some1,"cool");
char* some2 = malloc(1);
sprintf(some2,"face");
printf("%s ",some1);
printf("%s\n",some2);
}
Please, could anyone spot some light on what’s going on when memory is being allocated.
You are invoking undefined behavior. Absolutely anything can happen at this point, including what you might expect.
What’s actually happening is that the system does allocate memory to you in larger chunks. So while you’re outside of the bounds as defined by your program, you haven’t overstepped the buffer as far as the system goes. Almost all implementations do this; it’s easier for the system to keep track of 16 byte chunks, say, than it is to do so on a byte-by-byte basis.