简体   繁体   中英

use malloc out of main

I need to declare a global big sized array. I tried to use malloc out ouf main:

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#define LENGTH 200000

double *u_data = malloc(LENGTH * sizeof(double));
double *u_data_old = malloc(LENGTH * sizeof(double));
double *psi = malloc(LENGTH * sizeof(double));

void main(void){

    free(u_data);
    free(u_data_old);
    free(psi);
}

but I receive this error: initialiser element is not constant. Does anyone know how to solve this problem?

In C, execution begins at the main function, and there is no mechanism to run dynamic global initializers before that (unlike in C++). This means that global variables can only be initialized with compile-time constant expressions, but not with values that need to be determined dynamically.

The simple answer is that your malloc calls should move into the main function.

void * p;
int main() {
    p = malloc(X);
    // ...
    free(p);
}

However, this may not even be necessary. If you want a fixed amount of space, you can simply define a global array:

double data[HUGE];

int main() {
    // ...
}

This array has static storage duration (as opposed to the automatic storage duration of local variables), and there are virtually no size restrictions of static storage. Practically, the memory for global objects is set aside already at program load time, and it is not part of the dynamically managed memory at all.

You need special place in the executable part where you allocate memory (and I see that you understand this idea for deallocation). But you can declare you variable anyware.

So, solution is following:

double *u_data = NULL;
double *u_data_old = NULL;
double *psi = NULL;

void main(void){
    u_data = malloc(LENGTH * sizeof(double));
    u_data_old = malloc(LENGTH * sizeof(double));
    psi = malloc(LENGTH * sizeof(double));

    {...}

    free(u_data);
    free(u_data_old);
    free(psi);
}

Malloc and free can only allocate and free up memory into the heap memory area during execution time, so using them out of the main function is incorrect.

The solution would be the code provided by ilya: declaring global variables and initializing them from the main 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