CWE-469: Use of Pointer Subtraction to Determine Size(使用指针减法以确定大小)

 ID: 469

类型:基础
结构:简单

状态:草稿

描述

应用程序为了确定大小而采用指针减法,但是如果两个指针不在同一内存块的话会导致计算错误。

相关视图

与“研究层面”视图(CWE-1000)相关

与“开发层面”视图(CWE-699)相关

引入模式

阶段

说明

实现

 

应用平台

语言

C (出现的可能性不确定)

C++ (出现的可能性不确定)

后果

范围

冲击

可能性

访问控制
完整性
保密性
可利用性

技术冲击: 执行未获授权的代码或命令;获取特权或身份

存在拥有脆弱程序权限执行任意代码的风险。

 

被利用的可能性:

一般

示例

例1

以下示例包含用于确定链接列表中节点数的方法大小。方法将向链接列表的头传递一个指针。

(问题代码)

Example Language:

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:


...

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

CWE Cross-section

属于

971

SFP Secondary Cluster: Faulty Pointer Use

属于

1160

SEI CERT C Coding Standard - Guidelines 06. Arrays (ARR)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值