ID: 469 类型:基础 | 状态:草稿 |
描述
应用程序为了确定大小而采用指针减法,但是如果两个指针不在同一内存块的话会导致计算错误。
相关视图
与“研究层面”视图(CWE-1000)相关
与“开发层面”视图(CWE-699)相关
引入模式
阶段 | 说明 |
实现 |
应用平台
语言
C (出现的可能性不确定)
C++ (出现的可能性不确定)
后果
范围 | 冲击 | 可能性 |
访问控制 | 技术冲击: 执行未获授权的代码或命令;获取特权或身份 存在拥有脆弱程序权限执行任意代码的风险。 |
被利用的可能性:
一般
示例
例1
以下示例包含用于确定链接列表中节点数的方法大小。方法将向链接列表的头传递一个指针。
(问题代码)
Example Language: C
struct node {
int data;
struct node* next;
};
// Returns the number of nodes in a linked list from
// the given pointer to the head of the list.
int size(struct node* head) {
struct node* current = head;
struct node* tail;
while (current != NULL) {
tail = current;
current = current->next;
}
return tail - head;
}
// other methods for manipulating the list
...
但是,该方法创建一个指向列表末尾的指针,并使用指针减法通过从头部指针中减去尾部指针来确定列表中的节点数。无法保证指针存在于同一内存区域中,因此以这种方式使用指针减法可能返回不正确的结果并允许其他意外行为。在本例中,应该使用计数器来确定列表中的节点数,如下代码所示。
(正确代码)
Example Language: C
...
int size(struct node* head) {
struct node* current = head;
int count = 0;
while (current != NULL) {
count++;
current = current->next;
}
return count;
}
应对措施
阶段: 实现 保存索引变量。这是建议的解决方案。与其互相减去指针,不如使用与所讨论的指针大小相同的索引变量。使用此变量从一个指针“漫游”到另一个指针并计算差异。请务必检查这个号码。 |
种属
关系 | 类型 | ID | 名称 |
属于 | 740 | CERT C Secure Coding Standard (2008) Chapter 7 - Arrays (ARR) | |
属于 | 874 | CERT C++ Secure Coding Section 06 - Arrays and the STL (ARR) | |
属于 | 884 | ||
属于 | 971 | ||
属于 | 1160 |