获取无法分配内存错误

时间:2011-07-28 17:05:42

标签: c++ c linux gcc

我的程序中出现此错误...

mprotect: Cannot allocate memory 

ulimit -a 给出输出:

core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 20
file size               (blocks, -f) unlimited
pending signals                 (-i) 16382
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 1024
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) unlimited
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

我想要保护的内存量是60 MB。有人能告诉我问题是什么以及如何解决?

2 个答案:

答案 0 :(得分:2)

Return Value

On success, mprotect() returns zero.
On error, -1 is returned, and errno is set appropriately.

Errors

EACCES
The memory cannot be given the specified access. This can happen, for example, if
you mmap(2) a file to which you have read-only access, then ask mprotect() to
mark it PROT_WRITE.

EFAULT
The memory cannot be accessed.

EINVAL
addr is not a valid pointer, or not a multiple of PAGESIZE.

ENOMEM
Internal kernel structures could not be allocated.
Or: addresses in the range [addr, addr+len] are invalid for the address space of
the process, or specify one or more pages that are not mapped.

鉴于错误消息,您可能遇到ENOMEM错误,并查看错误代码,这并不一定意味着无法分配内存。您可能具有无效的地址范围,或者(很可能)您的页面未映射。

不要试图在一个膨胀的泡沫中保护这么大的记忆。鉴于虚拟内存如何工作,可能性太大,以至于不会映射该巨大块中的某些页面。在调用mprotect之前,您需要确保映射有问题的页面(页面)。

当您使用系统函数时,最好阅读该函数的手册页。然后重新阅读它。手册页有时可能有点简洁。

答案 1 :(得分:0)

虽然我认为这不是你的问题,但也应该注意mprotect由于分配失败肯定会失败,至少有两个原因:

  1. 如果仅在VMA的一部分上更改权限,则内核必须将其拆分为两个VMA。此拆分需要资源分配,并且可能会失败。 (请注意,munmap也可能由于同样的原因而失败!)
  2. 将非脏页面从只读状态更改为可写状态时,会增加进程的提交费用。在严格禁止过度使用的系统上,当物理内存/交换耗尽时,提交费用的这种“分配”可能会失败。
相关问题