【发布时间】: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