The following code works, but when I change my size larger than 10 I get segmentation faults. I'm pretty sure it has to do with the pointer somehow I just can't figure it out!
I need to make my matrix larger, by setting the matrix[SIZE][SIZE] to size 10000.
#define SIZE 100
It only works whenamatrix[SIZE][SIZE] to size 100.
#define SIZE 10
Any help will be greatly appreciated! Thanks!
Endomlic
Code:
//I had to change the size to 10 from 100 because
//of segmentation faults
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#include <sys/types.h>
#define SIZE 10 <---------------------------HERE
struct matrix
{
int C[SIZE][SIZE];
}*c_ptr;
int A[SIZE][SIZE], B[SIZE][SIZE];
void randomize(int dim, int);
void compute_element(int, int);
void print();
int main(int argc, char * argv[])
{
int shmid, status;
int i,j,l,m,z, children = 1;
pid_t pid;
shmid = shmget((key_t)1234, sizeof(int) * SIZE * SIZE, 0666 | IPC_CREAT);
c_ptr = shmat(shmid, 0, 0);
// place random values in A and B
randomize(SIZE,10000);
//Spawns chlidren based on user parameter
//default is 1
if(!(argc < 2))
{
children = atoi(argv[1]);
}
printf("%d process(es) spawned. To spawn more processes type number after program name.\n", children);
pid = fork();
if(pid == 0){
for( l = 0; l < (SIZE/2); l++ ){
for( m = 0; m < (SIZE/2); m++ )
{
for(z = 0; z < children; z++){
pid = fork();
if(pid == 0){
(void) shmat(shmid, 0, 0);
compute_element(l,m);
//exit child
_exit(status);
}
}
}
}
//exit child
_exit(status);
}
//the other half the parent will handle
for( i = (SIZE/2); i < SIZE; i++ ){
for( j = (SIZE/2); j < SIZE; j++ )
{
(void) shmat(shmid, 0, 0);
compute_element(i,j);
}
}
//wait for child to exit before printing
wait(&status);
print();
return 0;
}
void randomize(int dim, int big)
{
int i,j;
for( i = 0; i < dim; i++ )
for( j = 0; j < dim; j++ )
{
A[i][j] = random() % big;
B[i][j] = random() % big;
}
}
void compute_element(int iNum, int jNum)
{
int k;
{
c_ptr->C[iNum][jNum] = 0;
for( k = 0; k < SIZE; k++ )
if( (k % 2) == 0 )
c_ptr->C[iNum][jNum] += A[iNum][k] * A[k][jNum];
else
c_ptr->C[iNum][jNum] -= A[iNum][k] * A[k][jNum];
}
}
void print()
{
int i;
for(i = 0; i < SIZE; i++)
{
int row = random() % SIZE;
int col = random() % SIZE;
printf("C[%d][%d] = %d\n", row, col, c_ptr->C[row][col]);
}
}