Search code examples
cfunctionparametersprogram-entry-point

How can the called (derived) function access the variables of the caller (base) function in c language?


Consider the following code:

void foo(){
   .....
}
int main()
{
    int arr[3][3] ;
    char string[10];
    foo();
    return 0;
}

How can the function foo access the locals of my main function without passing the parameters to the function as function arguments ? Does the function foo have enough privileges to access and modify the variables in main ? please reply thank you


Solution

  • As per the C language specification, a function's local variables are inaccessible to other functions. There is no legal, supported way to do what you're asking. That said, in most (all?) implementations of the C language the main function's variables will be stored on the stack, which is easy to locate and can be read and written by anyone (it has to be because everyone needs to store local information in it) so it is technically possible (though it is a remarkably bad idea).

    void foo(){
        int b; // puts a 4 byte word on the stack atop the return address
        (&b)[2]; // interpret b as the first entry in an array of integers (called the stack)
        // and offset past b and the return address to get to a
        // for completeness
        (&b)[0]; // gets b
        (&b)[1]; // gets the return address
    }
    int main()
    {
        int a; // puts a 4 byte word on the stack
        foo(); // puts a (sometimes 4 byte) return address on the stack atop a
        return 0;
    }
    

    This code, might, on some systems (like 32 bit x86 systems) access the variables inside of the main function, but it is very easily broken (e.g. if pointers on this system are 8 bytes, if there's padding on the stack, if stack canaries are in use, if there are multiple variables in each function and the compiler has its own ideas about what order they should be in, etc., this code won't work as expected). So don't use it, use parameters because there's no reason not to do so, and they work.