C Programming - Stack Segment


#include < stdio.h >
main()
{
char i=10;
char *ptr=&i;
unsigned long j;
for(j=0; j<4294967296; j++) printf("%u -- %d\n",ptr+j, *(ptr+j));
}

Platform used: Redhat Linux E.L 4.0 on Intel P4 2.8Ghz

We got a SEG fault when (ptr+j) crosses 3GB. Why?


It does not seem to be an authentic explanation to me as well, but learn something from this.

PAE (Physical Address Extension) enabled kernel will support physical memory greater than 4GB upto 64GB which a CPU can address. Process under a kernel which is not enabled with PAE support can only address upto 4GB of which 1GB is reserved by kernel

Linux uses segmentation + paging for memory management. It uses 4 segments

Code Segment (Kernel Space)
Data/Stack Segment (Kernel Space)
Code Segment (User Space)
Data/Stack Segment (User Space)

Kernel Space is from 0xC0000000 - 0xFFFFFFFF ( 3GB - 4GB)
User Space is from 0x00000000 - 0xBFFFFFFF ( 0GB - 3GB)
 
4 GB--->| | |
| Kernel | | Kernel Space (Code + Data/Stack)
| | __|
3 GB--->|----------------| __
| | |
| | |
2 GB--->| | |
| Tasks | | User Space (Code + Data/Stack)
| | |
1 GB--->| | |
| | |
|________________| __|
0x00000000

Labels:


About this entry