我的程序中出现此错误...
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。有人可以告诉我问题是什么以及如何解决吗?
最佳答案
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 之前映射有问题的页面。
当您使用系统函数时,阅读该函数的手册页总是一个好主意。然后再读一遍。手册页有时可能有点简洁。
关于c++ - 出现无法分配内存错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6862825/