Cannot declare array of size 400000 in C

孤人 提交于 2019-12-08 04:44:52

问题


I am trying to do following:

#include <windows.h>
#include <stdio.h>
#define N 400000

void main() {
    int a[N];
}

I get a stackoverflow exception. My computer has 6GB of main memory so I cant be using it all up. How do I solve this problem? I using VS 2008 on Windows 7 and coding in C.


回答1:


The amount of stack size you're allowed to use is never going to be the full amount of main memory.

You can use this flag to set the stack size--which defaults to 1MB. To store 400,000 ints you'll need at least 1.526 MB.

Why not allocate this on the heap instead of the stack?




回答2:


When you define a variable like that, you're requesting space on the stack. This is the managed section of memory that's used for variables in function calls, but isn't meant to store large amounts of data.

Instead, you'd need to allocate the memory manually, on the heap.

int *a = (int *) malloc(sizeof(int) * N);

This defines a as a pointer to the memory on the heap. This will behave the same as the array, except you will need to manually

free(a);

when you finish using it or you'll create a memory leak.




回答3:


Automatic variables are allocated on the stack, which is usually 1MB. To solve this, allocate the memory on the heap:

int *a = (int*)malloc(sizeof(int) * N);

When you're done with that memory, you can deallocate it:

free(a);

That will return the memory to the system.




回答4:


You need Stack Size larger than 400000*4=1600000 Bytes ~ 1.6 MB but the default stack size in visual studio is 1MB. There is 2 solutions:

1- you can change the stack size of you program by:

  • right click project, and choose properties from the menu .
  • go to Configuration properties->Linker->Commandline, add this parameter

    /STACK:2000000

2- dynamic array to allocate over the heap, instead of static array , as all have said.



来源:https://stackoverflow.com/questions/7212645/cannot-declare-array-of-size-400000-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!