【问题标题】:C error message: "Reading invalid data from ***** : the readable size is '28' bytes, but '32' bytes may be read."C 错误消息:“从 ***** 读取无效数据:可读大小为 '28' 字节,但可以读取 '32' 字节。”
【发布时间】:2020-07-31 23:43:44
【问题描述】:

下面的代码只是我真实代码的sn-p。我有一个二叉树并获取要插入的节点。 我必须对插入的节点和 3 个前任节点和 3 个后继节点做一些事情。 如果未找到节点,则 searchNode 返回 NULL。我想防止一遍又一遍地搜索 7 个节点。因此,如果它们足够接近,我考虑将它们转移到键值与先前键值相比的差异。

gcc 编译器给了我这个警告:

"Reading invalid data from 'scope': the readable size is '28' bytes, but '32' bytes may be read."

在该代码行上:scope[k] = scope[k + diff];。我猜是因为 scope[k + diff] 可能超出了定义的范围,但我看不到上面的 if 语句会发生这种情况。

struct Node
{
    long key;
    struct Node* left;
    struct Node* right;
    int height;
};

struct Node* searchNode(struct Node* root, long key)
{

    if (root == NULL || root->key == key) {
        return root;
    }
    if (key < root->key)
        return searchNode(root->left, key);
    else
        return searchNode(root->right, key);
}

int main(){

    struct Node* scope[7];
    int flag1 = 0;
    int preKey = 0;
    int diff = 0;
    int xKey = 0;
    struct Node* temp = NULL;
    
    // Node inserted
    temp = searchNode(tree, xKey);

    if (flag1 == 0) { //for the first element checked
        flag1 = 1;
    SCOPE:;
        preKey = temp->key;
        scope[0] = searchNode(tree, xKey - 3);
        scope[1] = searchNode(tree, xKey - 2);
        scope[2] = searchNode(tree, xKey - 1);
        scope[3] = temp;
        scope[4] = searchNode(tree, xKey + 1);
        scope[5] = searchNode(tree, xKey + 2);
        scope[6] = searchNode(tree, xKey + 3);
    }
    else {
        diff = temp->key - preKey;
        if (diff > 6)
            goto SCOPE;
        else {
            for (int k = 0; k < 7 - diff; k++) {
                scope[k] = scope[k + diff];
            }
            for (int j = 7 - diff; j < 7; j++) {
                scope[j] = searchNode(tree, temp->key + j - 3);
            }
            preKey = temp->key;
        }
    }             
}

【问题讨论】:

  • 那里的goto SCOPE 让我头疼。考虑在没有 goto 的情况下进行重写,这样它更易读且不易碎。
  • @calculuswhiz 新版本的 gcc 可以在编译时进行范围检查。 Werror 错误
  • @dekrion 例如,您在哪里检查差异是否为负数..
  • 如果你在你的代码中放一个tree的例子会很有帮助。

标签: c tree binary-tree binary-search-tree


【解决方案1】:

有问题的行是:

scope[k] = scope[k + diff];

给定 if 语句,编译器可以推断在执行该行时,diff ≤ 6,但 diff 也可以是任何负数。所以 diff 在 { -∞ .. 6 } 中。 它可以知道k在{0 .. 12}范围内,包括在内。 这意味着 k + diff 必须在 { -∞ .. 18 } 范围内。 但范围仅从 0 到 7。 因此,您很可能会尝试从未分配的地址读取。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-08
    • 2019-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 2021-11-10
    相关资源
    最近更新 更多