慎用mmap[key]!!!

本文详细介绍了在C++中使用Map容器判断元素存在性的正确方法,并对比了错误方法可能导致的问题,强调了使用count函数的重要性。
#include <cstdio>
#include <cstring>
#include <map>
using namespace std;
#include <iostream>

int main() {
	map<string, int> mmap;
	cout << "Before test: ";
	for (map<string, int>::iterator it = mmap.begin();
			it != mmap.end(); ++it) cout << it->first << " ";
	cout << endl << endl;
	
	cout << "test:" << endl;
	if (mmap["ZhengDongjian"] == 0) {
		cout << "string \"ZhengDongjian\" doesn't exist." << endl << endl;
	}
	cout << "Insert ZhengDongjian: ";
	pair<map<string, int>::iterator, bool> res = mmap.insert(make_pair("ZhengDongjian", 1));
	if (res.second) cout << "Insert success!" << endl;
	else cout << "Insert failed!" << endl << endl;

	cout << "After that: ";
	for (map<string, int>::iterator it = mmap.begin();
			it != mmap.end(); ++it) cout << it->first << " ";
	cout << endl << "Test over..." << endl;

	return 0;
}

可以看出,如果使用operator[](const string& _str).根据返回结果是否为0来判断该元素是否存在于map中是不靠谱的,因为这会导致该元素(键)被直接插入,而这可能是你绝对不想做的!所以,不要自觉没有问题就用它(⊙o⊙)哦.

在判断元素是否存在map中应适用count函数:

if (mmap.count("ZhengDongjian") != 0) {
    cout << "string already exist!" << endl;
} else {
    cout << "string doesn't exist!" << endl;
}


### **错误原因分析** `mem_test -o 0x88000000 4 10` 命令报错 **`mmap Error !!! (22)`**,错误代码 **22** 对应 **`EINVAL`**(Invalid argument),通常由以下原因导致: --- ### **可能原因及解决方案** #### 1. **地址未对齐或超出范围** - **原因**:`0x88000000` 可能未按内存页对齐(通常需 4KB 对齐),或超出进程可访问的物理/虚拟地址范围。 - **解决**: - 检查地址是否对齐(如对齐到 `0x1000` 的倍数): ```bash echo "obase=16; $((0x88000000 % 0x1000))" | bc # 若结果非0,则未对齐 ``` - 调整地址为对齐值(如 `0x88001000`)。 #### 2. **权限不足** - **原因**:目标地址空间无读写权限(如内核保留区域)。 - **解决**: - 使用 `root` 用户运行(已满足)。 - 检查 `/proc/iomem` 确认地址是否可访问: ```bash grep -i 88000000 /proc/iomem ``` #### 3. **内存映射长度无效** - **原因**:参数 `4`(长度)或 `10`(次数)可能不合法(如长度为 0 或过大)。 - **解决**: - 确保长度为正整数且小于系统限制(如 `getconf PAGE_SIZE` 的整数倍)。 - 尝试调整参数:`mem_test -o 0x88000000 4096 1`(4KB 对齐长度)。 #### 4. **内核配置限制** - **原因**:内核未启用 `CONFIG_STRICT_DEVMEM` 或地址被保护。 - **解决**: - 临时关闭保护(需重启生效): ```bash echo 0 > /proc/sys/kernel/yama/ptrace_scope ``` - 重新编译内核时禁用 `CONFIG_STRICT_DEVMEM`(需管理员权限)。 #### 5. **硬件/驱动问题** - **原因**:目标地址对应的硬件未初始化或驱动异常。 - **解决**: - 检查硬件手册确认 `0x88000000` 是否为合法物理地址。 - 加载对应内核驱动(如 `modprobe`)。 --- ### **调试步骤** 1. **检查系统日志**: ```bash dmesg | tail -n 20 ``` 2. **使用 `strace` 跟踪系统调用**: ```bash strace mem_test -o 0x88000000 4 10 ``` 3. **验证工具合法性**: - 确认 `mem_test` 工具适用于当前平台(如 ARM/x86)。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值