0

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?

aboria
  • 123
  • 6
  • `4099` is exceeding array bounds -> undefined behaviour – Stephan Lechner Jan 28 '19 at 23:03
  • 5
    Thanks for asking. First of all, this is undefined behavior so an implementation is free to do whatever it wants. That said, in practice, there is no guarantee that the buffer you allocated was allocated on a page boundary. It's likely that something in the internal C libraries/runtime already allocated some memory so your allocation for `p` ended up spanning across a page boundary, or by some luck `p[4099]` is some other piece of memory that you corrupted by writing to it. – nanofarad Jan 28 '19 at 23:04
  • It is a duplicate really, there are hundreds of questions asking why the program survived when the OP believed it "should have crashed". – Weather Vane Jan 28 '19 at 23:06
  • 3
    You're not talking to your operating system, you're talking to `malloc`. `malloc` has no concept of pages. – melpomene Jan 28 '19 at 23:08
  • None of those two links are good duplicates. They don't address the page thing. – melpomene Jan 28 '19 at 23:11

1 Answers1

4

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