Question

Suppose I have a function that looks like this:

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? 
}

My (naive) assumption is that if I searched the entire stack and registers for addresses to the root node, root->right and its children (on the heap) right before fun returns, I would find none. Is this a fair assumption? If so, could there be exceptions for any architecture that you can think of? How would that happen?

Was it helpful?

Solution

Your assumption is wrong for most platforms and environments. Data values can be kept in some registers or stack cells even if they aren't anymore from those ones. It's fully compiler's responsibility to put proper values in registers and cells according to the used calling convention and to comply with the required functionality, but nothing more is guaranteed. That's why e.g. local variables are filled with garbage on function entry: they keep some previous values, not cleared after some work finished.

Some tasks require data cleaning (e.g. deleting password contents after its applying) but this is done using explicitly coded cleaning of memory regions.

If you are thinking on languages with garbage collecting, that's another but similar story.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top