简体   繁体   中英

Dynamically allocating memory without using malloc

I have been writing a program where I have a 2d array that changes size if the user wants , as follows:

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

int max_length = 1024;
int memory_length = 16;
int block_length = 64;

void process_input(int memory[memory_length][block_length], char* user_input) {
    ...
}

int main(void) {
    printf("Not sure what to do? Enter 'help'\n");
    while (0 == 0) {
        int memory[memory_length][block_length];
        char user_input[max_length];
        printf(">> ");
        fgets(user_input, max_length, stdin);
        printf("\n");
        process_input(memory, user_input);
        if (user_input[0] == 'e' && user_input[1] == 'n' && user_input[2] == 'd') {
            break;
        }
        printf("\n");
    }
    return 0;
}

NOTE: The process_input() function that I made allows the user to play around with the values inside the array 'memory' as well as change the value of memory_length or block_length , hence then changing the length of the array. After the user is done the cycle repeats with a fresh array. I can use the 2d array perfectly fine, parsing it to any function. However one day I discover that there are functions such as malloc() that allow you to dynamically allocate memory through a pointer. This made me then question:

Should I re-write my whole very complicated program to use malloc and other 'memory functions', or is it okay to keep it this way?

Also as a side question that might be answered by answering the main question:

Every time I declare the 2d array, does the previous contents of the array get free, or do I keep filling up my memory like an amateur?

Finally if there is anything else that you may notice in the code or in my writing please let me know.

Thanks.

Should I re-write my whole very complicated program to use malloc and other 'memory functions', or is it okay to keep it this way?

Probably rewrite it indeed. int memory[memory_length][block_length]; in main() is a variable-length array (VLA). It is allocated with automatic storage and gets the size of those size variables at the point where its declaration is encountered, then it can't be resized from there.

For some reason a lot of beginners seem to think you can resize the VLA by changing the variables originally used to determine it's size, but no such magic relation between the VLA and those variables exists. How to declare variable-length arrays correctly?

The only kind of array in C that allows run-time resizing is one which was allocated dynamically. The only alternative to that is to allocate an array "large enough" and then keep track of how much of the array you actively are using - but it will sit there in memory (and that is likely no big deal).

However, it is not recommended to allocate huge arrays with automatic storage, since those usually end up on the stack and can cause stack overflows. Use either static storage duration or allocated storage (with malloc etc).

Every time I declare the 2d array, does the previous contents of the array get free, or do I keep filling up my memory like an amateur?

You can only declare it once. In case you do so inside a local scope, with automatic storage duration, it does indeed get cleared up every time you leave the scope which it was declared. But that also means that it can't be used outside that scope.

Finally if there is anything else that you may notice in the code or in my writing please let me know.

Yes, get rid of the global variables. There is no reason to use them in this example, avoid them like the plague. For example a function using an already allocated array might pass the sizes along, like in this example:

void process_input (size_t memory_length, 
                    size_t block_length,
                    int    memory[memory_length][block_length], 
                    char*  user_input)

In C, local variables, ie variables declared within a function, are allocated on the stack. They are only allocated once when the function is first called. The fact that you can declare variables within a while loop can lead to some confusion. The loop does not somehow allocate the memory again and again.

The memory allocated for all local variables is released when the function return.

The main reason that you might want declare a variable inside a loop (besides convenience) is to limit the scope of the variable. In your code above, you cannot access the "memory" variable outside of the while loop. You can easily check this for yourself. Your compiler should raise an error.

Whether the stack or the heap contains more memory depends on your computer architecture. In an embedded system you can often specify whether to allocate more or less memory to the heap or the stack. On a computer with virtual memory, such as a PC, the size of the heap and the stack are only limited by the size of your hard drive and the address space.

Allocating arrays on the heap is not as simple as it might seem. Single dimensional arrays work just as you might imagine, but things get more complicated with multidimensional arrays, so it is probably better to stick with either a locally or statically declared array in your case.

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