linux下的malloc,隐式限制
发布时间:2020-12-14 01:27:58 所属栏目:Linux 来源:网络整理
导读:对不起,如果标题不像它应该的那样具有描述性,那么问题很难用几句话来表达.我试图通过malloc’ing找出我有多少内存,如果有效,写入该段.在某些系统上(x86_64上的所有 linux),我在写入2049th mib时看到了段错误.代码是: #include stdio.h#include stdlib.h#inc
对不起,如果标题不像它应该的那样具有描述性,那么问题很难用几句话来表达.我试图通过malloc’ing找出我有多少内存,如果有效,写入该段.在某些系统上(x86_64上的所有
linux),我在写入2049th mib时看到了段错误.代码是:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/mman.h> int main (int argc,char **argv) { void *addr; int megasize = 2100 /// allocate the memory via mmap same result //addr = mmap ((void *) 0,(size_t) megasize << 20,PROT_READ | PROT_WRITE,// MAP_PRIVATE | MAP_ANONYMOUS,(int) -1,(off_t) 0); addr = malloc(megasize << 20); if (addr == MAP_FAILED) { fprintf (stderr,"alloc of %d megabytes failed %sn",megasize,strerror (errno)); exit (1); }; printf ("got %d megabytes at %pn",addr); { int i; char *p = addr; printf("touching the %d Mb memory:n",megasize); for (i = 0; i < megasize; i++) { p[i << 20] = 0; putchar('.'); if (i%64==63) // commenting out this line i see that it really is the 2049th mb printf(" #%dn",i); fflush(stdout); }; putchar('n'); }; /// free the memory munmap (addr,(size_t) megasize << 20); return 0; } 它在某些系统上可靠地进行了段落,而在其他系统上,它可以正常工作.读取失败的系统的日志告诉我它不是oom杀手.我可以选择megasize的值,这将导致malloc失败,但那些更大. 我相信有一个限制,我没有观察到malloc没有观察到,我无法弄清楚它是什么.我尝试通过getrlimit读出一些限制,这些限制似乎与RLIMIT_AS和RLIMIT_DATA相关,但那些更大. 这是我的valgrindlog的相关部分 ==29126== Warning: set address range perms: large range [0x39436000,0xbc836000) (defined) ==29126== Invalid write of size 1 ==29126== at 0x400AAD: main (in /home/max/source/scratch/memorytest) ==29126== Address 0xffffffffb9436000 is not stack'd,malloc'd or (recently) free'd 谁能告诉我一个问题是什么? 解决方法
通过int i计数时会出现溢出,因为int在这里是4个字节宽:
p[i << 20] = ... 更改 int i; 成为 size_t i; size_t是寻址内存时的首选类型. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |