0

I have executed this dumb code for some testing:

int main(){

    char a[4];
    a[3000] = '2';  //no problem
    sleep(30);
    printf("wake up\n");
    a[20000] = '2'; //segmentation fault
    printf("No segmentation fault!\n");
    while(1);

}

I know that this is so dumb (creating a 4 bytes array and wanting to store at the position 3000 and at the position 20000) but, as I said, it's only for testing. What I wanted to test is if accessing to a page reserved for stack space will result in a Segmentation Fault. It shouldn't, but it did!

How I know that the page that belongs to the a[20000] is a reserved page for this process? Well, during the sleep(30) time I watched the content of /proc/pid/maps and I got this:

7ffdce868000-7ffdce889000      rw-p 00000000 00:00 0                          [stack]

If you look at starting and finishing directions of the stack, you will see that an access to a[20000] is covered by this directions, since OS has assigned for that moment 33 pages of stack (which is 135168 Bytes). On those pages the process has reading and writing permision.

So, why did I got segmentation fault??

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
isma
  • 143
  • 1
  • 6
  • 3
    Have your program print the address of `a`. Compare that address to the bounds of the stack segment. Redo your calculations of whether `a[20000]` is in range. – zwol Jul 05 '20 at 02:11
  • 3
    I think what zwol is trying to suggest to you is that a[20000] is actually at a higher stack address than where your array `a` starts, not a lower one. The stack grows down but the array you are writing to beyond the end is writing to higher memory addresses. Try `a[-20000]` – Michael Petch Jul 05 '20 at 02:23
  • Even if the memory page is reserved for the stack, that does not necessarily mean that the memory has actually been allocated yet. Depending on your operating system, you may have to perform [stack probing](https://geidav.wordpress.com/tag/stack-probing/) to trigger the growth of the stack. – Andreas Wenzel Jul 05 '20 at 02:39
  • The stack grows down; your array will be near the *top* of that mapping. Only argv[] and envp[] and a couple stack frames of parents of `main` are above main's stack frame on the stack. – Peter Cordes Jul 05 '20 at 03:45
  • @AndreasWenzel: Right, but anything that shows up in `/proc/PID/maps` *has* already been allocated. The problem is that the stack will only grow downward. (But yes, if you did allocate a huge local array, the compiler would have to `sub rsp, big_number` *before* accessing the array. [How is Stack memory allocated when using 'push' or 'sub' x86 instructions?](https://stackoverflow.com/q/46790666)). – Peter Cordes Jul 05 '20 at 03:48

0 Answers0