[英]Segmentation Fault(Core Dumped) Code shows this error
我一直在嘗試使用線程來乘以多維數組。 在代碼正確執行的同時,我不斷收到此特定錯誤
#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,不勝感激。
首先,您使用=
進行比較,如下所示:
if(array = NULL){
fprintf(stderr,"No Memory\n");
return;
}
它應該是:
if(array == NULL){
fprintf(stderr,"No Memory\n");
return;
}
另外,這是錯誤的:
int i,j,*k,v,Sum=0;
k=(int *)arg;
v=(int)k;
v
不是像k
和其他許多錯誤的指針...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.