繁体   English   中英

使用 rand() 时 C 中的写入访问冲突错误

[英]Write Access Violation error in C while using rand()

我对使用 C 编程很陌生,所以希望有人能容忍我并帮助我解决我面临的问题。

我正在编写一个代码来使用蒙特卡罗方法估计 pi 的值。 但是,当我构建和调试时,我收到一条错误消息:

“抛出异常:写访问冲突。a 是 0x1110112。

我在这行代码中的 generate_random_array function 中收到此错误:

a[i] = (((double)rand() / (double)RAND_MAX) * 2.0 ) - 1.0;

我也发布了整个代码以供参考。

注意:我正在使用带有 MSVC 编译器的 Visual Studio

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void generate_random_array(int sz, double a[]);
void count_points_inside_circle(int sz, double x[], double y[], int* counter);

int main()
{
    int tot = 1000000000;
    int incircle_c = 0;
    double  distance_sq, pi;
    double* x = NULL;
    double* y = NULL;
    

    /*create arrays in the heap*/
    x = malloc(tot * sizeof(double));
    y = malloc(tot * sizeof(double));

    /*generate random locations*/
    generate_random_array(tot, x);
    generate_random_array(tot, y);

    /*count the points inside te circle by checking the location distance*/

    count_points_inside_circle(tot, x, y, &incircle_c);

    /*estimate pi*/
    pi = 4.0 * incircle_c / (double)tot;
    
    printf("pi estimated value using %d samples was found to be %lf", tot, pi);
    
    free(x);
    free(y);
    return 0;

}

void generate_random_array(int sz, double a[]) {
    int i;
    srand(time(NULL));
    for (i = 0; i < sz; i++) 
        a[i] = (((double)rand() / (double)RAND_MAX) * 2.0 ) - 1.0;

}

void count_points_inside_circle(int sz, double x[], double y[],int* counter_p) {
    int i;
    double distance_sq;

    for (i = 0; i < sz; i++) {
        distance_sq = x[i] * x[i] + y[i] * y[i];
        if (distance_sq <= 1)
            (*counter_p)++;
    }
}

您必须始终对照NULL检查从malloc返回的指针。 例如:

x = malloc(n * sizeof *x);
if (x == NULL) { /* Handle the failure and/or exit */ }

另一方面,此任务根本不需要使用数组(或用作数组的分配空间); 您只需要圆内的点数和生成的总点数。 可以这样简单地完成:

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

double estimate_pi (unsigned trial_count)
{
    const double rr = (double)RAND_MAX * RAND_MAX;
    unsigned inner_point_count = 0;
    unsigned i;
    for (i = 0; i < trial_count; ++i) {
        double x = rand();
        double y = rand();
        if (x * x + y * y <= rr)
            ++inner_point_count;
    }
    return 4.0 * inner_point_count / trial_count;
}

int main (void)
{
    printf("%f\n", estimate_pi(1000000000));

    return 0;
}

请注意,标准库使用的随机数生成器的质量会显着影响此模拟的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM