If I understand it correctly, Linux will actually try to be smart when I make a request to allocate memory, and allocate a page at a time? So when I make a call to malloc to request 100 bytes, it will actually allocate a page size instead (4096 bytes I think)?
The reason I'm asking is because I was looking at some really funky code someone else has written, and the only reason I can think of that it works is that dynamic memory allocation works like I have described above.
The code below will only work because an entire memory page is allocated and set to zero, so the string will automatically become null terminated even though the code is not really allocating enough space for the nul character.
Code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
size_t len;
const char s[] = "Hello";
char *p;
len = strlen(s+1); /* What the hell was he thinking? */
printf("len = %d\n", len);
p = calloc(1, len);
if (!p)
return 1;
memcpy(p, s, len+1);
printf("s is now: '%s'\n", p);
return 0;
}