由于在更改巨大页面分配的大小时initialize()函数导致的分段错误

当我使用大页面分配的内存大小时,我在程序中遇到分段错误,即,当我定义LENGTH = 4 * 1024时,存在seg错误。 当我定义4 * 1024 * 1024时,没有seg错误。 这是什么原因?

代码如下:

#define _POSIX_C_SOURCE 199309 #define _GNU_SOURCE #include  #include  #include  #include  #include  #include  #include  #include  #include  #define PROTECTION (PROT_READ | PROT_WRITE) #define LENGTH (4*1024) //#define LENGTH (4*1024*1024) #define LINE_SIZE 64 #define ASSOC 16 #define CACHE_SIZE (4*1024*1024) #define WAY_SIZE (CACHE_SIZE/ASSOC) #ifndef MAP_HUGETLB #define MAP_HUGETLB 0x40000 #endif #define ADDR (void *) (0x0UL) #define FLAGS (MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB) int main (int argc, char *argv[]){ ... // allocate a buffer with the same size as the LLC using huge pages buf = mmap(ADDR, LENGTH, PROTECTION, FLAGS, 0, 0); if (buf == MAP_FAILED) { perror("mmap"); exit(1); } set_S = atoi(argv[1]); set_M = atoi(argv[2]); printf("test 0\n"); initialize(set_S); printf("test 1\n"); initialize(set_M); printf("test 2\n"); head_S = &buf[set_S*LINE_SIZE]; printf("test 3\n"); head_M = &buf[set_M*LINE_SIZE]; ... } 

请注意,我的计算机默认没有启用大页面,所以我以root身份启用它:

 echo 20 > /proc/sys/vm/nr_hugepages 

这是我打开大页面后/ proc / meminfo中的巨大页面相关信息:

 HugePages_Total: 20 HugePages_Free: 20 HugePages_Rsvd: 0 HugePages_Surp: 0 Hugepagesize: 2048 kB 

节目输出:

 $./a.out 1 1 test 0 Segmentation fault (core dumped) 

$ uname输出:

 Linux mymachine 3.13.0-43-generic #72-Ubuntu SMP Mon Dec 8 19:35:06 UTC 2014 x86_64 x86_64 x86_64 GNU/Linux 

编辑1:添加初始化函数:

 void initialize(int set){ int j, k; char ** ptr1, ** ptr2; char * tmp; // re-initialize pointer array of size "size" // implementation of Sattolo's random cyclic permutation for (j=0; j=1; j--){ k = rand()%j; ptr1 = (char **)&buf[set*LINE_SIZE+j*WAY_SIZE]; ptr2 = (char **)&buf[set*LINE_SIZE+k*WAY_SIZE]; tmp = *ptr1; *ptr1 = *ptr2; *ptr2 = tmp; } } 

当访问set*LINE_SIZE+(ASSOC-1)*WAY_SIZE = set*64 + CACHE_SIZE - WAY_SIZE = set*64 + 4*1024*1024 - WAY_SIZEinitialize循环中大于mmap长度LENGTH = 4*1024时, 你正在访问内存超出范围 。 这就是定义LENGTH = 4 * 1024时出现段故障的原因。