# 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;
}
}
}
i'm posting again the whole code cause i am not really sure where the segmentation fault is. i think now that it might be shared memory that causes the problem. thanks for the information about counting argv.
For an array of length
argc-2, only indexing of0toargc - 3are valid. So thisis wrong because you are accessing
array[argc - 2]. It should be:Note that there might be other errors causing the segmentation fault because you didn't provide how you call the program.
It's better to be defensive to process command line arguments. (i.e, check the validity of
argc, etc).