- 论坛徽章:
- 0
|
如下代码在执行完free之后,内存会交还给系统,也就是说used在free()之后会减少很多;
如果把#if 1 改成 #if 0,则内存似乎没有还给系统。这是什么原因呢。
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #if 1
- #define MALLOC_BLOCK_COUNTS 1024
- #define MALLOC_BLOCK_SIZE (2 * 1024 * 1024)
- #else
- #define MALLOC_BLOCK_SIZE 1024
- #define MALLOC_BLOCK_COUNTS (2 * 1024 * 1024)
- #endif
- static char *ptr[MALLOC_BLOCK_COUNTS];
- int
- main(int argc, char **argv)
- {
- long long i, j;
- memset(ptr, 0x0, sizeof(ptr));
- for (i = 0; i < MALLOC_BLOCK_COUNTS; i++) {
- ptr[i] = malloc(MALLOC_BLOCK_SIZE);
- if (ptr[i] == NULL) {
- perror("malloc()");
- exit(-1);
- }
- for (j = 0; j < MALLOC_BLOCK_SIZE; j++) {
- *(ptr[i] + j) = j % 256;
- }
- }
- for (i = 0; i < MALLOC_BLOCK_COUNTS; i++) {
- free(ptr[i]);
- }
- printf("ok\n");
- sleep(1000);
- return 0;
- }
复制代码 |
|