use*_*497 3 c stack-overflow arrays
我很久没有使用过C了,而且我在用CSV填充2D数组时遇到了问题.文件格式如下:
节点,输入,输出
1,200,10393
...
这实际上是链表的数组表示.有150000个元素,每当我尝试填充数组时,我得到一个错误,说"在main.exe中0x000000013facb957处未处理的异常:0xC00000FD:堆栈溢出." 我在64位机器上使用16GB RAM,而我正在使用带有x64构建配置的VS C++ 2010 Express.
int main(int argc, char *argv[])
{
int counter = 0;
char line [ 1024 ];
int map[150000][2] = {0};
char *comma = ",";
char *token;
int index;
int in, out;
char* end;
int nodeID;
FILE *fp;
fp = fopen("mapsorted.txt","r"); // read mode
if( fp == NULL )
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
//Skip header line
fgets ( line, sizeof line, fp );
while ( fgets ( line, sizeof line, fp ) != NULL) /* read a line */
{
//first part - the index for storage
token = strtok(line,comma);
index = strtol(token,&end,10);
//second part
token = strtok(NULL,comma);
in = atoi(token);
//third part
token = strtok(NULL,comma);
out = atoi(token);
//store in array
map[index][0] = in;
map[index][1] = out;
}
fclose ( fp );
}
Run Code Online (Sandbox Code Playgroud)
当我分配一个较小的数组时,代码似乎工作,但是当它很大时,它会失败.我想我应该有足够的内存来处理这个大小的数组.
小智 7
int map[150000][2];
Run Code Online (Sandbox Code Playgroud)
似乎至少有2*4*150000字节(假设采用现代32位架构),大约为1.2MB.知道现代操作系统通常会设置几兆字节的堆栈大小,这实际上可能是问题所在.您的计算机具有几千兆字节的RAM并不意味着您的进程可以使用它,特别是不在堆栈中.对于大型数组,请尝试malloc()在堆上使用一些内存:
int (*map)[2] = malloc(sizeof(*map) * 150000);
Run Code Online (Sandbox Code Playgroud)
要么
int *map = malloc(150000 * 2 * sizeof(*map));
Run Code Online (Sandbox Code Playgroud)
(注意第二种情况下的尺寸!),或者static将其声明为将其移出堆栈空间:
static int map[150000][2];
Run Code Online (Sandbox Code Playgroud)
或者简单地使它成为一个全局变量来实现类似的行为:
int map[150000][2];
void foo()
{
...
}
Run Code Online (Sandbox Code Playgroud)