【问题标题】:Random number generation code not working [Probably a stack overflow]随机数生成代码不起作用[可能是堆栈溢出]
【发布时间】:2015-06-30 23:25:04
【问题描述】:

此 C 代码应生成 100 万个随机数。在多次编译代码时,我使用 srand() 来解决伪随机生成问题。我认为理论上这段代码应该可以工作,但它似乎遗漏了一些可能导致溢出的东西。知道为什么它在执行过程中停止工作吗?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main()
{
    FILE *ofp;
    int k=0, i=1000000;;
    int array[i];

    ofp=fopen("output.txt","w");
    while (ofp==NULL)
    {
        printf("File is corrupted or does not exist, \nplease create or fix the file and press enter to proceed");
        getchar();
    }

    srand(time(NULL));
    rand();

    for (k=0;  k<1000000; k++)
    {
        array[k] = rand()%100;
        fprintf(ofp, "%d\n", array[k]);
    }

    return 0;
}

【问题讨论】:

  • 您遇到的错误是什么?
  • 1,000,000 int 的数组在 32 位机器上占用 4MB,所以是的,您可能溢出了堆栈。将数组声明为static,将其设为全局,或使用malloc 创建。
  • 使用代码块作为 IDE,程序停止工作(这是错误消息)。

标签: c random overflow generator time.h


【解决方案1】:

将您的代码修复如下:

// ...
#define MAX 1000000
// ...

int main() {

int array[MAX];   // proper static allocation

// ...

if (ofp == NULL) { // while loop has no meaning in here

 // ...  }

 // ... 

 return 0;

 }

并且不要忘记在完成后关闭您打开的流以将分配的资源释放回系统(在您的情况下,您的进程最终将被终止,所以如果您懒得关了)

编辑:根据 C99 规范,它允许使用某些类型来初始化静态分配的数组,但 C89 不允许。此外,为避免可能的堆栈溢出问题,请尝试通过调用 ma​​lloccalloc 函数在代码中动态分配数组。例如:

 // ...
 #include <stdlib.h>
 // ...
 int main()
 {
 // ...
 int* array = malloc(sizeof(int) * i);

 // ...
 free(array); // don't forget to free it after you're done.

  return 0;
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 2019-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    相关资源
    最近更新 更多