malloc的实现,在linux下的实现是这样的,当所需要分配的内存大于128k,会用mmap(匿名映射)来实现。小于128k使用在堆分配(改天会分析下malloc函数的源码实现)。
这里还有几个
mallopt(int param,int value);
这个函数能设置一些内存分配管理的参数,也就是设置param为value的值(比如我们想要强制所分配的内存是mmap分配的)。具体的参数可以去看man手册。
使用这个很简单,就是在使用malloc之前设置就好了。
struct mallinfo mallinfo(void);
可以看下mallinfo结构体的结构;
- struct mallinfo {
- int arena; /* non-mmapped space allocated from system */
- int ordblks; /* number of free chunks */
- int smblks; /* number of fastbin blocks */
- int hblks; /* number of mmapped regions */
- int hblkhd; /* space in mmapped regions */
- int usmblks; /* maximum total allocated space */
- int fsmblks; /* space available in freed fastbin blocks */
- int uordblks; /* total allocated space */
- int fordblks; /* total free space */
- int keepcost; /* top-most, releasable (via malloc_trim) space */
- };
也就是一些内存分配的统计信息。
还有就是在栈上复制字符串,我们可以用alloca+strcpy来实现,或者可以使用linux特别提供的2个函数:
- char *strdupa(char *s);
- char *strndupa(char *s)
下面来介绍locking memory
- mlock (const void *addr,size_t len)
- int mlockall(int flags)
第一个函数是锁住一段虚拟地址空间,第二个函数是锁住本进程的整个地址空间。
解锁用下面两个函数:
- munlock (const void *addr,size_t len)
- int munlockall(int flags)
由于locking memory对系统影响很大,因此这里系统有些限制。
可以看下man手册中的这段
引用
In Linux 2.6.8 and earlier, a process must be privileged (CAP_IPC_LOCK)
in order to lock memory and the RLIMIT_MEMLOCK soft resource limit
defines a limit on how much memory the process may lock.
Since Linux 2.6.9, no limits are placed on the amount of memory that a
privileged process can lock and the RLIMIT_MEMLOCK soft resource limit
instead defines a limit on how much memory an unprivileged process may
lock.
in order to lock memory and the RLIMIT_MEMLOCK soft resource limit
defines a limit on how much memory the process may lock.
Since Linux 2.6.9, no limits are placed on the amount of memory that a
privileged process can lock and the RLIMIT_MEMLOCK soft resource limit
instead defines a limit on how much memory an unprivileged process may
lock.