gpt4 book ai didi

c - 调用 srand() 时遇到读取变量错误(无法访问地址处的内存)

转载 作者:行者123 更新时间:2023-11-30 19:41:01 25 4
gpt4 key购买 nike

我正在尝试使用 Codeblocks IDE 和 gcc 在 C 中进行并发编程。当我运行程序时,我没有收到任何输出。但有趣的是,当我在程序中的某个点放置断点时,程序将执行该点之前的所有指令(包括向控制台输出值)。但是,之后,如果我尝试执行指令 srand(time(NULL)),我正在观察的所有变量都会立即显示“读取变量时出错,无法访问地址 X 处的内存”并且调试过程停止。

这是我的 main() 函数

/*main function*/
int main()
{
int k = 3;
int m = 100;
int n = 10;
int t = 10;

/*First, let's create the threads*/
pthread_t thread[numOfThreads];

/*Second, create the data struct*/
struct programData *data = malloc(sizeof(struct programData));

/*Initialize data struct*/
data->kPumps=k;
data->mVisitors=m;
data->nCars=n;
data->tTime=t; /*They'll drive visitor around for 10 units of time.*/

/*Now let's create the different threads*/
pthread_create(&thread[0], NULL, visitorThread, (void*)data);
pthread_create(&thread[1], NULL, carThread, (void*)data);
pthread_create(&thread[2], NULL, pumpThread, (void*)data);
pthread_create(&thread[3], NULL, gasTruck, (void*)data);

return 0;
}

还有我的访客线程

void *visitorThread(void *arg){
int arrayIndex;
int i;
/*Let's create mVisitors*/
struct programData *data;
data = (struct programData*)arg;
int numOfVisitors;
numOfVisitors = data->mVisitors;
/*create an array of visitors*/
struct visitor v[numOfVisitors];

/*Initialize values*/
for(i = 0; i < numOfVisitors; i++){
v[i].id = i+1;
v[i].isInCar = false;
v[i].isInQueue = false;
}

printf("There are %d visitors at the San Diego Zoo \n", numOfVisitors);
printf("At first the visitors wait at the snake exhibit \n");
//sleep(5);
printf("Now some of them are getting bored, and want to get into a car to be shown the rest of the zoo \n");

/*After a random amount of time, some people line up to take cars*/
/*create queue*/
struct visitor* queue[numOfVisitors];
/*Initialize the array*/
for(i = 0; i < numOfVisitors; i++){
queue[i] = NULL;
}

arrayIndex = 0;

/*While there are people in the snake exhibit*/
while(numOfVisitors >=1){
/*After a random period of time, no more than 5 seconds...*/
//srand
srand(time(NULL));
int timeBeforePersonLeaves = rand()%5+1;
//fflush(stdout);
//sleep(timeBeforePersonLeaves);
/*...a random person will get bored and enter the array line to be picked up by a car*/
srand(time(NULL));
int personIndex = rand() % numOfVisitors;
queue[arrayIndex] = &v[personIndex];
v[personIndex].isInQueue = true;
printf("Visitor %d is now in queue spot %d \n", personIndex, arrayIndex);
arrayIndex++;
}
return;
}

问题似乎存在于 while 循环中。如果我在 while 循环末尾的括号处放置一个断点,它将输出每个值。但是,如果将断点放在 while 循环内的任何位置,一旦到达 srand 调用,就会导致同样的问题。任何有关此问题的帮助将不胜感激,并提前致谢。

最佳答案

while(numOfVisitors >=1)。你有一个无限循环。导致arrayIndex持续增长并溢出队列。另外,请阅读 srand 的手册页。您只需要调用一次,而不是连续调用。 – 凯勒姆

关于c - 调用 srand() 时遇到读取变量错误(无法访问地址处的内存),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34056958/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com