使用malloc时我注意到指定的指针为null。我想在执行代码期间将大约30 MB的内存分配给堆内存。如何在Ubuntu 12.04 LTS上使用GCC 4.6.3作为编译器?我应该分配更多的堆栈内存吗?它会更好吗?
由于
编辑代码中有问题的部分,代码在if语句之后终止。
#include <stdio.h>
#include <math.h>
#include <limits.h>
#include <stdlib.h>
#define a0 0.53
#define N LONG_MAX
// This value of N is the highest possible number in long double
// data format over 100. Higher is not possible due to the size of
// the default heap memory. Change its value to adjust the precision of
// integration and computation time. Since exponential decays really fast
// a modest value of N is enough for this integration.
// The discrete integral may be defined as follows:
long double trapezoid(long double x[],long double f[]) {
int i;
long double dx = x[1]-x[0];
long double sum = 0.5*(f[0]+f[N]);
for (i = 1; i < N; i++)
sum+=f[i];
return sum*dx;
}
main() {
printf("LONG_MAX constant has the following value: %ld \n", LONG_MAX);
long double * P = malloc(N * sizeof(long double));
long double * r = malloc(N * sizeof(long double));
long double * PP = malloc(N * sizeof(long double));
// The if statement is to check if the memory allocation has
// been done and terminate the program otherwise.
if (P == 0 || r == 0)
{
printf("ERROR: Out of memory\n");
return 1;
}
// Declare and initialize the loop variable
}