开发者

How to fix memory bug in my c program?

It was showing errors as Array size too lar开发者_JAVA技巧ge, Structure size too large, too much global data defined in a file. Please show me how to allocate dynamic memory?

struct
{
   doublereal a[25000000];

} _BLNK__;
static doublereal x[22500]  /* was [3][7500] */;

static doublereal vn[12], del, eul[22500]   /* was [3][1500] */;


Allocate the data on the heap, rather than on the stack. Use pointers and allocate the memory in an initialization routine.

Also, do some calculations to work out if you have enough memory e.g. 25000000 * 16 bytes => 400MB of memory. (no idea how big doublereal is).


try dynamic memory allocation with malloc and pointer like:

typedef struct
{
   doublereal a[25000000];    
} _BLNK__;    
...
{    
_BLNK__ *mypointer = malloc(sizeof*mypointer);
mypointer->a[0] = 0;
mypointer->a[1] = 1;
...
free(mypointer);
}
...


The statement

doublereal a[25000000];

allocates memory on the stack. There is a strict limit on the size of the stack, and you can find it on a linux or osx system by running:

$ ulimit -s
8192

which is 8192K = 8M.

You are trying to allocate 25000000 * 8 = 200000000 bytes = 190 M on a 32 bit system, which is much larger than the limit.

You have three choices:

1) reduce the size of the array

2) dynamically allocate memory (doublereal *a = (doublereal *)malloc(sizeof(doublereal) * 25000000))

3) increase stack size (but this requires administrative privileges on all machines that this program will run on)


#include <stdlib.h>

#define LEN_A (25000000)
struct
{
   doublereal* a;

}_BLNK__;

#define LEN_X (22500)
#define LEN_VN (12)
#define LEN_EUL (22500)


#define INIT_BLNK(x) x.a=(doublereal*)malloc(LEN_A*sizeof(doublereal))
#define FREE_BLNK(x) if(x.a!=0)free(x.a)

static doublereal *x;
static doublereal *vn,del,*eul;

int main()
{
   _BLNK__ Item;

   x = (doublereal*)malloc(LEN_X*sizeof(doublereal));
   vn = (doublereal*)malloc(LEN_VN*sizeof(doublereal));
   eul = (doublereal*)malloc(LEN_EUL*sizeof(doublereal));


   INIT_BLNK(Item);

   //Do whatever you wish


   //Return memory to the OS
   free(x);
   free(vn);
   free(eul);

   FREE_BLNK(Item);

   return 0;
}

Try using this. I just wrote the code here so if there are any compiler errors try to fix them

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜