C语言动态内存分配
#include <stdio.h>
#include <stdlib.h>
int main() {
int* dynamic_array = (int*)malloc(10 * sizeof(int)); // 分配10个整型空间
if (dynamic_array == NULL) {
fprintf(stderr, "内存分配失败");
return EXIT_FAILURE;
}
// 模拟数据写入
for (int i = 0; i < 10; i++) {
dynamic_array[i] = i * 2;
}
// 扩展内存至20个元素
int* resized = realloc(dynamic_array, 20 * sizeof(int));
if (resized) {
dynamic_array = resized;
} else {
free(dynamic_array); // 扩展失败时释放原内存
return EXIT_FAILURE;
}
free(dynamic_array); // 必须显式释放
return EXIT_SUCCESS;
}
关键点
malloc
与realloc
必须检查返回指针- 内存泄漏检测工具推荐:Valgrind、AddressSanitizer
- 最佳实践:遵循RAII原则(资源获取即初始化)
Python文件缓存管理
class SafeFileHandler: def __init__(self, filename): self.filename = filename def __enter__(self): self.file = open(self.filename, 'r+', buffering=1024) # 设置1KB缓冲区 return self.file def __exit__(self, exc_type, exc_val, exc_tb): if not self.file.closed: self.file.flush() # 强制写入磁盘 self.file.close() # 使用上下文管理器 with SafeFileHandler('data.log') as f: f.write('2025-12-20 09:00:00 [INFO] 存储操作开始n') # 异常发生时自动执行flush和close
优化策略
- 缓冲区大小根据文件类型调整(日志文件建议4KB倍数)
os.fsync()
确保元数据同步- 大文件处理推荐内存映射技术(mmap模块)
Java NIO直接内存操作
import java.nio.ByteBuffer;
public class DirectMemoryDemo {
public static void main(String[] args) {
// 分配200MB直接内存(跳过JVM堆)
ByteBuffer buffer = ByteBuffer.allocateDirect(200 * 1024 * 1024);
try {
buffer.putInt(0, 0xCAFEBABE); // 写入魔数
buffer.position(0);
System.out.println(Integer.toHexString(buffer.getInt()));
} finally {
// 显式清除(重要!)
if(buffer.isDirect()) {
((sun.nio.ch.DirectBuffer)buffer).cleaner().clean();
}
}
}
}
注意要点
- 直接内存不受GC管理,必须手动释放
- 性能优势:减少JVM堆与系统内存间的拷贝
- 监控工具:JDK Native Memory Tracking
常见问题解决方案
- 内存碎片
- 使用内存池技术(如Apache Commons Pool)
- C++推荐智能指针(shared_ptr/unique_ptr)
- 线程安全
- 读写锁保护共享内存区域
- 原子操作替代复杂锁(C++11 atomic)
- 缓存失效
- LRU算法实现(LinkedHashMap扩展)
- Redis分布式缓存方案
开发工具推荐
| 工具类型 | 推荐工具 |
|—————-|————————-|
| 内存分析 | VisualVM、JProfiler |
| 性能测试 | JMH、sysbench |
| 代码检查 | SonarQube、Coverity |
引用说明
本文代码实例参考:
- C11标准库文档(ISO/IEC 9899:2011)
- Python官方《PEP 343 — The “with” Statement》
- Oracle《Java NIO Programming Guide》
- 内存管理理论源自《计算机程序的构造和解释》(SICP)第二章
(本文完)