【发布时间】:2015-05-04 18:22:26
【问题描述】:
我一直在尝试使用线程来乘以多维数组。虽然代码正常执行,但我不断收到此特定错误
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<malloc.h>
#include<unistd.h>
#include<fcntl.h>
#include<errno.h>
#define R_FLAGS O_RDONLY
int arraySize;
int **oarray;
int **resultarray; /*the two multidimensional arrays declared*/
void *multiply(void *arg);
/*The function used to showcase Mutliplication*/
int** DynamicAllocate(int Size) {
int i;
int **array;
array = malloc(Size * sizeof(int *));
if(array = NULL){
fprintf(stderr,"No Memory\n");
return;
}
for(i=0;i<Size;i++){
array[i] = malloc(Size * sizeof(int));
/*using the same no of rows for the columns as instructed*/
if(array[i] == NULL){
fprintf(stderr,"No Memory\n");
return;
}
}
return array;
}
void *multiply(void *arg) {
int i,j,*k,v,Sum=0;
k=(int *)arg;
v=(int)k;
for(i=0;i<arraySize;i++){
for(j=0;j<arraySize;j++){
Sum= Sum + oarray[v][j]*oarray[j][i];
}
Sum = resultarray[v][i];
Sum=0;
}
}
int main(int argc, char *argv[]){
int error,*join;
char nrows,*intarray;
int row,i,j,value=0;
pthread_t tid;
if((error = open("File",O_RDONLY))==-1){
perror("Unable to Open File");
}
read(error,&nrows,1);
row = atoi(&nrows);
arraySize = row;
oarray = DynamicAllocate(row);
resultarray = DynamicAllocate(row);
intarray = malloc(1024); /*read until given file ends*/
read(error,intarray,1024);
printf("****Assignment # 3****\n");
printf("****By:Hammad Faisal****\n");
printf("****DDP-SP12-BCS-026****\n\n");
/*temporary array that is being used for storage and multiplication*/
for(i=0;i<row;i++){
for(j=0;j<row;j++){
oarray[i][j]=atoi(&intarray[value]);
value+=2;
}
}
/*using for loop to attach thread to each row allocated*/
for(i=0;i<row;i++){
join = (int *)i;
pthread_create(&tid,NULL,multiply,join);
pthread_join(tid,NULL);
}
/*display the resultant matrix*/
for(i=0;i<row;i++){
for(j=0;j<row;j++){
printf("%d\t",resultarray[i][j]);
}
printf("\n");
}
return 0;
}
上面提到的代码在 Ubuntu 上可以完美编译,但是分段错误是问题所在。每次我尝试执行代码时,它都会一遍又一遍地给出相同的错误,尽管从我阅读的内容来看,代码应该可以正常执行。 我是新的 Linux,我将不胜感激任何帮助。
【问题讨论】:
-
你用什么编译代码?
-
我做了一个make文件,这样代码就可以正常执行了。
-
在我看来,这里有一些关于类型转换和取消引用 ptrs 的错误。请仔细检查您的代码并确保所有类型转换、分配和取消引用/非取消引用都有意义。
-
您能否在问题中也包含输入文件内容?
-
创建一个线程然后立即在一个循环中加入它,除了最技术性的意义外,不会完成“多线程”。
标签: linux shell ubuntu multidimensional-array fault