【发布时间】:2013-12-21 17:10:38
【问题描述】:
假设我有一个如下所示的函数:
void fun() {
struct bintree {
struct bintree * left;
struct bintree * right;
};
// build a perfectly balanced 7-node bintree
struct bintree * root = malloc(sizeof(struct bintree));
root->left = malloc(sizeof(struct bintree));
root->right = malloc(sizeof(struct bintree));
root->left->left = malloc(sizeof(struct bintree));
root->left->right = malloc(sizeof(struct bintree));
root->right->left = malloc(sizeof(struct bintree));
root->right->right = malloc(sizeof(struct bintree));
// create a stack pointer to the left subtree of root
struct bintree * RL = root->left;
// remove pointer to root node from stack
root = NULL;
// could it be possible to find pointers to root, root->right and
// its children on the stack/registers?
}
我的(天真的)假设是,如果我在 fun 返回之前搜索整个堆栈并注册根节点、root->right 及其子节点(在堆上)的地址,我将找不到任何地址。这是一个公平的假设吗?如果是这样,您能想到的任何架构都会有例外吗?怎么会这样?
【问题讨论】:
-
我知道我会忘记一些事情。
-
好的。 now 如所写,您至少会编译。您假设以前的地址值不存在于内存或堆栈中的某个位置,这充其量是特定于平台的。从语言纯粹主义者的角度来看,您不需要关心。如所写,您肯定会泄漏内存。运行时库可能会将您的分配分配在某个堆链中,但是一旦您丢失对内存地址的唯一引用,就您的代码而言,它是“无法访问”的。
-
请记住,C 没有垃圾回收器 - 你忘记了
freeroot、root->left、root->left->left和root->left->right -
@Eric 我没有故意释放它们,因为它与问题无关。我可能应该更清楚这一点。
标签: c pointers stack cpu-registers