# include <stdio.h>
# include <stdlib.h>
# include <stddef.h>
# include <sys/types.h>
# include <sys/ipc.h>
# include <sys/shm.h>
# include <sys/sem.h>
# include <unistd.h>
# include <time.h>
# include <math.h>
int main(int argc, const char* argv[])
{
int i,j,x,shM, *shmPtr;
int *array_pid, *apotelesma, loops,y,N;
int *array1;
double a,b,temp;
shM=shmget(3002,sizeof(int),IPC_CREAT|0600);
shmPtr=(shM,0,0);
array1=(int*)malloc((argc-2)*sizeof(int));
if(array1==NULL)
printf("error in array1");
for (i=0;i<=(argc-2);i++)
{
array1[i]=atoi(argv[i]);
}
N=argc;
loops=atoi(argv[argc-1]);
array_pid=(int*)malloc(N*sizeof(int));
if (array_pid==NULL)
printf("error in array_pid");
apotelesma=(int*)malloc(N*sizeof(int));
if (apotelesma==NULL)
printf("error in apotelesma");
j=fork();
if (j>0)
{
array_pid[i]=j;
for (i=0;i<loops;i++)
{
srand(time(NULL));
if (i>0)
apotelesma[i]=*shmPtr;
y=(rand()%(argc-2));
array1[y]=*shmPtr;
printf("y=%d apotelesma=%d",y,apotelesma[i]);
}
*shmPtr=-1;
for (i=0;i<N;i++)
wait();
shmdt(shmPtr);
shmctl(shM,0,IPC_RMID);
exit(0);
}
else //child
{
while(1)
{
x=*shmPtr;
if(x<0)
{
exit(0);
}
a=rand();
b=rand();
temp=(pow((a-x/2),2)+pow((b-x/2),2));
temp=sqrt(temp);
if (temp<=x/2)
*shmPtr=1;
else
*shmPtr=0;
}
}
}我重新发布了整个代码,因为我不太确定分段错误在哪里。我认为现在可能是共享内存导致了这个问题。感谢您提供的关于计算argv的信息。
发布于 2014-11-27 23:15:56
对于长度为argc-2的数组,只有0到argc - 3的索引有效。所以这就是
for (i=1;i<=(argc-2);i++)是错误的,因为您正在访问array[argc - 2]。它应该是:
for (i = 0; i < argc - 2; i++)请注意,可能还有其他错误导致分段错误,因为您没有提供调用程序的方式。
最好是防御性地处理命令行参数。(即检查argc的有效性等)。
发布于 2014-11-27 23:21:41
在传递命令行参数时,最好在继续之前检查argc的值。
if(argc != /* num of arguments */)
return;
for (i=1;i<=(argc-2);i++)这是错误的。
它必须是
for (i=0;i<argc-2;i++)https://stackoverflow.com/questions/27173798
复制相似问题