简体   繁体   English

在主外使用malloc

[英]use malloc out of main

I need to declare a global big sized array. 我需要声明一个全局大数组。 I tried to use malloc out ouf main: 我试图使用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++). 在C中,执行从main函数开始,在此之前没有运行动态全局初始化程序的机制(与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. 简单的答案是,您的malloc调用应移入main函数。

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. Malloc和free只能在执行期间将内存分配并释放到堆内存区域中,因此在main函数之外使用它们是不正确的。

The solution would be the code provided by ilya: declaring global variables and initializing them from the main function. 解决方案将是ilya提供的代码:声明全局变量并从main函数初始化它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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