Linux System Programming 学习笔记(九) 内存管理
1. 进程地址空间
/* obtaining dynamic memory */ #include <stdlib.h> void * malloc (size_t size);
/* returns a pointer to a block of memory suitable for holding an array of nr elements, each of size bytes */ #include <stdlib.h> void * calloc (size_t nr, size_t size);
/* resizing (making larger or smaller) existing allocations */ #include <stdlib.h> void * realloc (void *ptr, size_t size);
/* actual allocation size of the chunk of memory pointed to by ptr */ #include <malloc.h> size_t malloc_usable_size (void *ptr);
#include <unistd.h> int brk (void *end); void * sbrk (intptr_t increment);
void *p; p = mmap (NULL, /* do not care where */ 512 * 1024, /* 512 KB */ PROT_READ | PROT_WRITE, /* read/write */ MAP_ANONYMOUS | MAP_PRIVATE, /* anonymous, private */ ?1, /* fd (ignored) */ 0); /* offset (ignored) */ if (p == MAP_FAILED) perror ("mmap"); else /* ‘p‘ points at 512 KB of anonymous memory... */
6. 基于栈的动态内存分配
/* make a dynamic memory allocation from the stack */ #include <alloca.h> void * alloca (size_t size);
for (i = 0; i < n; ++i) { char foo[i + 1]; /* use ‘foo‘... */ }
/* memset() sets the n bytes starting at s to the byte c and returns s */ #include <string.h> void * memset (void *s, int c, size_t n);
/* compares two chunks of memory for equivalence */ #include <string.h> int memcmp (const void *s1, const void *s2, size_t n);
因为结构体通常涉及到数据对齐,所以使用memcmp来比较两个结构体是不安全的
/* are two dinghies identical? (BROKEN) */ int compare_dinghies (struct dinghy *a, struct dinghy *b) { return memcmp (a, b, sizeof (struct dinghy)); }
上述代码不安全,应该分别比较每个结构体成员:
/* are two dinghies identical? */ int compare_dinghies (struct dinghy *a, struct dinghy *b) { int ret; if (a->nr_oars < b->nr_oars) return ?1; if (a->nr_oars > b->nr_oars) return 1; ret = strcmp (a->boat_name, b->boat_name); if (ret) return ret; /* and so on, for each member... */ }
/* copies the first n bytes of src to dst, returning dst */ #include <string.h> void * memmove (void *dst, const void *src, size_t n);
memmove可以正确处理内存区重叠的情况(部分dst位于src之内)
#include <string.h> void * memcpy (void *dst, const void *src, size_t n)
memcpy在内存区出现重叠时 属于未定义行为
/* scans the n bytes of memory pointed at by s for the character c */ #include <string.h> void * memchr (const void *s, int c, size_t n);
/* “locking”one or more pages into physical memory, ensuring that they are never paged out to disk */ #include <sys/mman.h> int mlock (const void *addr, size_t len);
mlock() locks the virtual memory starting at addr and extending for len bytes into physical memory
/* mlockall() locks all of the pages in the current process‘s address space into physical memory. */ #include <sys/mman.h> int mlockall (int flags);
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。