简体   繁体   中英

Free memory from stack in C

Just wondering if there is a way to free or reduce the memory allocated from the stack at runtime. Ex:

int num[10] = {1,2,3,4};

Can I free the 6*4 bytes (Assuming int requires 4 bytes) at runtime?

The memory used by local variables is reclaimed when the block they are defined in ends. They can't be free'ed the way dynamically allocated memory can.

If you need to adjust the amount of memory you're using, allocate memory with malloc / free :

int *num = malloc(NUM_BYTES);
...
int *tmp = realloc(num, NEW_NUM_BYTES);
if (tmp) num = tmp;
...
free(num);

Can I free the 6*4 bytes (Assuming int requires 4 bytes) at runtime?

No. Objects of automatic (or static) storage duration have fixed size for their lifetime, as determined by their declarations. If you want to use less space, then declare a smaller object.

If you are specifically declaring a small-ish array, you do not know until runtime just what size it needs to be, and you want to declare only as much as you actually need, then you may have the alternative of using a variable-length array. VLA support is optional in C2011, and VLAs carry some potential issues that fixed-length arrays do not, but if that's acceptable to you then you might do it like so:

void count_to(unsigned char max) {
    int numbers[max];
    for (int i = 0; i < max; i++) {
        numbers[i] = i + 1;
    }

    // ...
}

Note that VLAs may not have initializers, and that you can get yourself in trouble (eg overflow the stack) if you end up with VLAs larger than you accounted for.

Your main alternative is dynamic allocation. Allocating your arrays dynamically has code and often performance overhead, and it requires you to be sure to free the allocated memory, but all conforming implementations support it, and it typically supports much larger objects than VLAs do.

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