技术代码:程序与内存

1struct Node{
2  var value;
3  Node * next;
4};
5
6queue<Node *>freeNodes;
7Node node[maxn];
8
9void init(){
10    for(int i = 0;i < maxn;i++)
11        freeNodes.push(node[i]);
12}
13
14Node* newnode(){
15    Node* n = freeNodes.front();
16    n->next = NULL;
17    freeNodes.pop();
18    return n;
19}
20
21void deleteNode(Node* n){
22    freeNodes.push(n);
23}
参考地址:内存泄漏 内存碎片 内存池
1public static void main(String[] args) {
2		
3		//JVM的最大可用内存,可通过-Xmx设置,默认值为物理内存的1/4,设置不能高于计算机物理内存
4		//返回值单位是字节
5		long maxMemory = Runtime.getRuntime().maxMemory();	
6		//当前JVM空闲内存,因为JVM只有在需要内存时才占用物理内存使用,所以freeMemory()的值一般情况下都很小,
7		//而JVM实际可用内存并不等于freeMemory(),而应该等于maxMemory()-totalMemory()+freeMemory()
8		long freeMemory = Runtime.getRuntime().freeMemory();
9		//当前JVM占用的内存总数,其值相当于当前JVM已使用的内存及freeMemory()的总和,会随着JVM使用内存的增加而增加
10		long totalMemory = Runtime.getRuntime().totalMemory();
11		System.out.println("JVM最大可用内存:"+maxMemory);
12		System.out.println("当前JVM空闲内存:"+freeMemory);
13		System.out.println("当前JVM占用的内存总数:"+totalMemory);
14		System.out.println("JVM实际可用内存:"+(maxMemory-totalMemory+freeMemory));
15	}
参考地址:查看JVM内存信息的方法
1<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
2<%
3String path = request.getContextPath();
4String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
5%>
6
7<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
8<html>
9  <head>
10    <base href="<%=basePath%>">
11    
12    <title>My JSP 'inlineBinding.jsp' starting page</title>
13    
14	<meta http-equiv="pragma" content="no-cache">
15	<meta http-equiv="cache-control" content="no-cache">
16	<meta http-equiv="expires" content="0">    
17	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18	<meta http-equiv="description" content="This is my page">
19	<!--
20	<link rel="stylesheet" type="text/css" href="styles.css">
21	-->
22<script type="text/javascript">
23//对象在内存中的表现形式
24//对象名存储在栈内存中,同时存在的还有一个指向堆内存的访问地址(如果对象有属性不为空)
25//在堆内存中存储的是对象的各属性的取值
26//需要说明的是值类型的数据直接存储在栈内存中
27function Person(){
28	
29}
30//开辟栈内存
31var p1 = new Person();
32//开辟堆内存
33p1.name = 'zhangsan';
34p1.age = 20;
35//开辟栈内存
36var p2 = new Person();
37//堆内存指向为空
38alert(p2.name);//undefined
39//p2堆内存
40p2 = p1;
41alert(p2.name);//zhangsan
42//清除栈内存
43//p2 = null;
44//访问堆内存
45//alert(p1.name);//zhangsan
46//清除栈内存
47p1 = null;
48//访问堆内存
49alert(p2.name);//zhangsan
50
51</script>
52  </head>
53  
54  <body>
55</body>
56</html>
参考地址:关于javascript内存分配
1//共享内存IPC简单示例
2//
3//使用方法:程序名 路径名 消息内容
4//
5#include <unistd.h>
6#include <stdio.h>
7#include <errno.h>
8#include <stdlib.h> 
9#include <string.h>
10
11#include <sys/ipc.h>
12#include <sys/shm.h>
13#include <fcntl.h>
14
15int 
16main(int argc, char** argv)
17{
18    int    shmid ;           //共享内存区的标识符
19    size_t shmSize = 512  ;  //共享内存的大小
20    char*  shmaddr ;         //共享内存的指针    
21     int  i = 0 ;
22
23    if (argc != 3)
24    {
25        perror("parameter error!\n") ;
26        exit(0) ;
27    }
28    
29    //创建共享内存
30    shmid = shmget(ftok(argv[1], 0), shmSize, IPC_CREAT) ;
31
32    //获取共享内存的指针(把共享内存映射到本进程地址空间)
33    shmaddr = shmat(shmid, NULL, 0) ;
34
35    //向共享内存中写入数据
36    strcpy(shmaddr, argv[2]) ;
37
38    //断开与共享内存的连接
39    shmdt(shmaddr) ;
40    exit(0) ;
41}
42
43//共享内存IPC简单示例
44//访问共享内存
45//
46//使用方法:程序名 同一路径名 消息内容
47//
48#include <unistd.h>
49#include <stdio.h>
50#include <errno.h>
51#include <stdlib.h> 
52#include <sys/ipc.h>
53#include <sys/shm.h>
54#include <fcntl.h>
55
56int 
57main(int argc, char** argv)
58{
59    int   shmid ;           //共享内存区的标识符
60    key_t shmkey ;          //共享内存区的key
61    char  msgbuf[512] ;     //存储从共享存储区提取的消息
62    char*  shmaddr ;        //共享内存的指针  
63 
64    if (argc != 2)
65    {
66        perror("parameter error!\n") ;
67        exit(0) ;
68    }
69    
70    //打开共享内存
71    shmid = shmget(ftok(argv[1], 0), 0, 0) ;
72
73    //把共享内存映射到本进程地址空间
74    shmaddr = shmat(shmid, NULL, 0) ;
75
76    //读取共享内存中的消息
77    printf("The message in the share memory : %s\n", shmaddr) ;
78
79    //断开与共享内存的连接
80    shmdt(shmaddr) ;
81    //删除共享内存
82    shmctl(shmid, IPC_RMID, NULL) ;
83
84    exit(0) ;
85}
参考地址:UNIX/Linux进程间通信IPC系列(七)共享内存区
1/*小内存块结构*/
2typedef struct{
3	char data[SMALLSIZE];/*存放data域*/
4}small_block;
5
6/*大内存块结构 */ 
7typedef struct{
8	char data[BIGSIZE];/*存放data域*/
9}big_block;
10
11/*小内存块管理结构*/ 
12typedef struct{
13	small_block * base_add;/*小内存块的基地址*/
14	int busy_num;/*被使用的数量 */
15	char busy[SMALLNUM];/*每个小内存块的使用情况*/ 
16}small_block_manage;
17
18/*大内存块管理结构*/ 
19typedef struct{
20	big_block * base_add;/*大内存块的基地址*/
21	int busy_num;/*被使用的数量 */
22	char busy[BIGNUM]; /*每个大内存块的使用情况*/ 
23}big_block_manage;
参考地址:【内存管理】Vxworks内存管理
1// Windows系统CPU内存网络性能统计第一篇 内存 GlobalMemoryStatusEx
2//By MoreWindows-(http://blog.csdn.net/MoreWindows)
3#include <stdio.h>
4#include <windows.h>
5
6const int KB_DIV = 1024;
7const int MB_DIV = 1024 * 1024;
8
9
10int main()
11{
12	printf("    Windows系统CPU内存网络性能统计第一篇 内存 GlobalMemoryStatusEx\n");      
13	printf(" -- By MoreWindows( http://blog.csdn.net/MoreWindows ) --\n\n"); 
14
15	MEMORYSTATUSEX memStatusEx; 
16	memStatusEx.dwLength = sizeof(memStatusEx);
17	if (GlobalMemoryStatusEx(&memStatusEx))
18	{
19		printf ("当前内存使用率: %d%%\n", memStatusEx.dwMemoryLoad);
20
21		printf ("系统物理内存总量: \t%I64dKB (%I64dMB)\n", memStatusEx.ullTotalPhys / KB_DIV, memStatusEx.ullTotalPhys / MB_DIV);
22		printf ("当前可用物理内存: \t%I64dKB (%I64dMB)\n", memStatusEx.ullAvailPhys / KB_DIV, memStatusEx.ullAvailPhys / MB_DIV);
23
24		printf ("系统虚拟内存总量: \t%I64dKB (%I64dMB)\n", memStatusEx.ullTotalVirtual / KB_DIV, memStatusEx.ullTotalVirtual / MB_DIV);
25		printf ("当前空闲虚拟内存: \t%I64dKB (%I64dMB)\n", memStatusEx.ullAvailVirtual / KB_DIV, memStatusEx.ullAvailVirtual / MB_DIV);
26
27		printf ("系统页面文件总量: \t%I64dKB (%I64dMB)\n", memStatusEx.ullTotalPageFile / KB_DIV, memStatusEx.ullTotalPageFile / MB_DIV);
28		printf ("当前空闲页面文件: \t%I64dKB (%I64dMB)\n", memStatusEx.ullAvailPageFile / KB_DIV, memStatusEx.ullAvailPageFile / MB_DIV);
29	}
30	return 0;
31}
参考地址:Windows系统CPU内存网络性能统计第一篇 内存
1void
2ngx_destroy_pool(ngx_pool_t *pool)
3{
4    ngx_pool_t          *p, *n;
5    ngx_pool_large_t    *l;
6    ngx_pool_cleanup_t  *c;
7
8    for (c = pool->cleanup; c; c = c->next) {   //依次执行每个清理函数
9        if (c->handler) {
10            c->handler(c->data);
11        }
12    }
13
14    for (l = pool->large; l; l = l->next) { //依次释放每个大块内存
15        if (l->alloc) {
16            ngx_free(l->alloc);
17        }
18    }
19
20    for (p = pool, n = pool->d.next; /* void */; p = n, n = n->d.next) {    //从内存池头节点开始,释放所有节点
21        ngx_free(p);
22        if (n == NULL) {
23            break;
24        }
25    }
26}
参考地址:nginx-----内存池
1object UnifiedMemoryManager {
2
3  private val RESERVED_SYSTEM_MEMORY_BYTES = 300 * 1024 * 1024
4
5  def apply(conf: SparkConf, numCores: Int): UnifiedMemoryManager = {
6    val maxMemory = getMaxMemory(conf)
7    new UnifiedMemoryManager(
8      conf,
9      maxHeapMemory = maxMemory,
10      onHeapStorageRegionSize =
11        (maxMemory * conf.getDouble("spark.memory.storageFraction", 0.5)).toLong,
12      numCores = numCores)
13  }
14 
15 //存储和执行内存的最大安全可用大小
16  private def getMaxMemory(conf: SparkConf): Long = {
17    val systemMemory = conf.getLong("spark.testing.memory", Runtime.getRuntime.maxMemory)//默认取最大可用内存
18    val reservedMemory = conf.getLong("spark.testing.reservedMemory",
19      if (conf.contains("spark.testing")) 0 else RESERVED_SYSTEM_MEMORY_BYTES) //系统预留内存,如有有设置spark.testing字段那么reservedMemory =0
20    val minSystemMemory = (reservedMemory * 1.5).ceil.toLong //系统需要的最小内存
21    if (systemMemory < minSystemMemory) { //当可用的内存小于系统需要的最小内存,就抛出异常
22      throw new IllegalArgumentException(s"System memory $systemMemory must " +
23        s"be at least $minSystemMemory. Please increase heap size using the --driver-memory " +
24        s"option or spark.driver.memory in Spark configuration.")
25    }
26=
27    if (conf.contains("spark.executor.memory")) { //判断单个节点设置的内存是否小于需要的最小内存
28      val executorMemory = conf.getSizeAsBytes("spark.executor.memory")
29      if (executorMemory < minSystemMemory) {
30        throw new IllegalArgumentException(s"Executor memory $executorMemory must be at least " +
31          s"$minSystemMemory. Please increase executor memory using the " +
32          s"--executor-memory option or spark.executor.memory in Spark configuration.")
33      }
34    }
35    val usableMemory = systemMemory - reservedMemory //存储和执行内存的可用内存
36    val memoryFraction = conf.getDouble("spark.memory.fraction", 0.6)//存储和执行内存的安全系数
37    (usableMemory * memoryFraction).toLong //存储和执行内存的最大安全可用内存 = 0.6 * (系统可用内存-预留内存)
38  }
39}
参考地址:Spark内存管理原理(上)
1//销毁内存池
2void
3ngx_destroy_pool(ngx_pool_t *pool)
4{
5    ngx_pool_t          *p, *n;
6    ngx_pool_large_t    *l;
7    ngx_pool_cleanup_t  *c;
8
9	//运行清理对象的handler
10    for (c = pool->cleanup; c; c = c->next) {
11        if (c->handler) {
12            ngx_log_debug1(NGX_LOG_DEBUG_ALLOC, pool->log, 0,
13                           "run cleanup: %p", c);
14            c->handler(c->data);
15        }
16    }
17
18	//释放大内存
19    for (l = pool->large; l; l = l->next) {
20
21        ngx_log_debug1(NGX_LOG_DEBUG_ALLOC, pool->log, 0, "free: %p", l->alloc);
22
23        if (l->alloc) {
24            ngx_free(l->alloc);		//使用free释放malloc申请的内存
25        }
26    }
27
28#if (NGX_DEBUG)
29
30    /*
31     * we could allocate the pool->log from this pool
32     * so we cannot use this log while free()ing the pool
33     */
34
35    for (p = pool, n = pool->d.next; /* void */; p = n, n = n->d.next) {
36        ngx_log_debug2(NGX_LOG_DEBUG_ALLOC, pool->log, 0,
37                       "free: %p, unused: %uz", p, p->d.end - p->d.last);
38
39        if (n == NULL) {
40            break;
41        }
42    }
43
44#endif
45
46	//释放每一个申请的内存池对象ngx_pool_t
47    for (p = pool, n = pool->d.next; /* void */; p = n, n = n->d.next) {
48        ngx_free(p);
49
50        if (n == NULL) {
51            break;
52        }
53    }
54}
55
56//重设内存池
57void
58ngx_reset_pool(ngx_pool_t *pool)
59{
60    ngx_pool_t        *p;
61    ngx_pool_large_t  *l;
62
63	//释放大内存
64    for (l = pool->large; l; l = l->next) {
65        if (l->alloc) {
66            ngx_free(l->alloc);
67        }
68    }
69
70	//内存池对象,仅仅改变last的指针位置
71    for (p = pool; p; p = p->d.next) {
72        p->d.last = (u_char *) p + sizeof(ngx_pool_t);	//导致所有的内存池对象的可用内存的起始地址偏移都一样
73        p->d.failed = 0;
74    }
75
76    pool->current = pool;
77    pool->chain = NULL;
78    pool->large = NULL;
79}
参考地址:【Nginx核心基础】内存池
1int main(void)
2{
3    u8 key;
4    u8 i = 0;
5    u8 *p = 0;
6    u8 *tp = 0;
7    u8 paddr[18];     //存放paddr+p地址的ASCII值
8    u8 sramx = 0;    //默认为内部sram
9    delay_init();        //延时函数初始化
10    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);    //设置中断优先级分组为组2
11    uart_init(115200);       //串口初始化为115200
12    LED_init();
13    KEY_init();
14    LCD_init();
15    FSMC_SRAM_Init();           //初始化外部SRAM
16    my_mem_init(SRAMIN);     //初始化内部内存池
17    my_mem_init(SRAMEX);    //初始化外部内存池
18    while()
19   {
20       key = KEY_Scan(0);        //不支持连按
21       switch(key)
22       {
23            case 0:                          //没有按键按下
24                break;
25            case KEY0_PRES:        //KEY0按下
26               p = mymalloc(sramx, 2048);    //申请2k字节
27               if(p != NULL)
28                    sprintf((char*)p, "Memory Malloc Test%03d", i);    //向p写入一些内容
29                break;
30            case KEY2_PRES:        //KEY2按下
31                myfree(sramx, p);        //释放内存
32                p = 0;
33                break;
34            case WKUP_PRES:        //KEY_UP按下
35                sramx = !sramx;           //切换当前malloc/free操作对象
36                break;
37       }
38       if(tp != p)
39       {
40            tp = p;
41            sprintf((char*)paddr, "paddr:0x%08x", (u32)tp);
42       }
43       delay_ms(10);
44       i++;
45       if((i%20) == 0)    //DS0闪烁
46       {
47           LED0 = !LED0;
48       }
49   }
50}
参考地址:内存管理实验_STM32F1开发指南_第四十二章

代码交流 2021