Search code examples
cpointersmemory-managementalloc

Understanding memory allocations and pointers in c


I am trying to deepen my understanding on Operating systems. My Linux system uses a page size of 4096 bytes. I got that from running the command:

[root@localhost]# getconf PAGESIZE
4096

I also know that a page is the least addressable memory unit. So I tried creating allocating exactly that: 4096 bytes for a char pointer and I began initializing as follows:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char *p = malloc(4096*sizeof(char));

    for(int i = 0 ;i< 4099;i++)
    {
        p[i] = 'c';
    }
    printf("Hey there!\n");

    return 0;
}

I know that chars are 1 byte size as well.

Here is what I don't understand, how come the program doesn't segmentfault even though, It should have exhausted the one page allocated for it!

This is not a duplicated question, the other questions are asking about pass the end of array addressing without the context of page size like I have here.

From my understanding, my pointer p should have have access to only one page of memory size i allocated 4096 bytes. If i have allocated 5000 bytes then it would have 2 pages, am i right?


Solution

  • Your issue likely has nothing to do with page size. When you malloc(PAGE_SIZE) you are not guaranteed to have your data start being allocated at the start of a page because that is not how heap allocation works. As others have mentioned your results will be undefined because it is like any case where you exceed array bounds.

    Also see the accepted answer here