简体   繁体   中英

Understanding how scoped arrays are stored

I'm confused how arrays are stored in the executable when they're within functions and the like.

With the code below I believe space for the value of the three ints to be stored is made in the executable.

#include <stdlib.h>

int main() {
    int arr[] = {rand(), rand(), rand()};
}

I was thinking for an array in a function, each call would use the same space as the other calls to store their array. But then I thought recursive calls would overwrite each others arrays. I don't get how space for them is left aside, especially with recursion and an unknown number of calls are made. I tried to make an example:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

bool myfunc(unsigned val) {
    int arr[] = {rand() % 10, rand() % 10};

    if (val == 0)
        return true;

    myfunc(val - 1);

    printf("%d %d\n", arr[0], arr[1]);
    return false;
}

int main() {
    myfunc(rand() % 50);
}

I get arrays elements are stored one after the other. But how is there space for them (in the stack?) when it's unkown how many there will be?

Objects defined with local scope in a function body with automatic storage (without a static keyword) are stored in temporary storage and reclaimed automatically upon exiting the corresponding scope.

Typical modern architectures use the runtime stack for this: the stack pointer register is decremented upon entering the scope by a fixed amount if the size is known at compile time, as is the case for your examples: int arr[] = {rand() % 10, rand() % 10}; defines an array of 2 int , usually 8 bytes.

If the size is only known at runtime, the stack pointer is decremented by a value computed at runtime, possibly causing undefined behavior if this size is too large. The stack pointer is restored to its original value upon leaving the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM