對不起,我是C++和linux的新手,我以前沒見過分段錯誤。我可以成功編譯該文件,但它只是輸出分段錯誤。Linux上的C++分段錯誤
我試圖谷歌分段錯誤,但仍然沒有線索如何解決我的代碼。
希望有人能救我並告訴我什麼是錯的通過具體說明我犯的錯誤。 我將不勝感激!非常感謝!
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <cstring>
#include <semaphore.h>
using namespace std;
#define NUM_THREADS 36
#define MAX 36
char matrix[6][6]; //result sheet
//queue elements
char queue[MAX], head=0, tail=0;
int row=0,col=0;
int runtime=1; // track the number of times we have run the dispatch
funciton
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void dispatch(){
row = runtime/6;
sleep(1); //wait 1 second to generate column number
col = runtime % 6 - 1;
if (runtime % 6 == 0)
col = 5;
runtime++;
}
void enqueue(char c){
queue[tail] = c;
tail = (tail+1)%MAX ;
}
char dequeue(){
char temp = queue[head];
head = (head+1)%MAX ;
return temp;
}
//master thread
void *qcTask(void *args) {
//simulate product convey delay
sleep(1);
pthread_mutex_lock(&mutex);
dispatch();
sleep(rand()%6+5);
if(rand()%100<90)
enqueue('Q');
else
enqueue('U');
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main (int argc, char* argv[]){
int input = atoi(argv[1]);
//error handling
if(argc!=2 || input < 0 || input>36){
cout<<"Input is illegal!";
}
else{
pthread_t threads[input];
int rc, i, count = 0;
srand(time(NULL));
for(i = 0;i<input;i++){
rc = pthread_create(&threads[i], NULL, qcTask, NULL);
if (rc){
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
for (i = 0; i < input; i++){
rc = pthread_join(threads[i], NULL);
if (rc){
cout << "Error:unable to join," << rc << endl;
exit(-1);
}
}
//initize matrix with default value 'i'
for (int i = 0; i < 6; i++){
for (int j = 0; j < 6; j++){
matrix[i][j] = 'I';
}
}
//fill the result sheet
for(int i=0;i<6;i++){
for (int j = 0; j < 6; j++){
matrix[i][j]=dequeue();
}
}
for (int i = 0; i < 6; i++){
for (int j = 0; j < 6; j++){
cout << matrix[i][j];
if (matrix[i][j] == 'U')
count++;
}
cout << endl;
}
cout << count << " products are unqualified.";
pthread_exit(NULL);
}
}
使用valgrind運行您的代碼 – pm100
歡迎來到Stack Overflow!這聽起來像你可能需要學習如何使用調試器來遍歷代碼。使用一個好的調試器,您可以逐行執行您的程序,並查看它與您期望的偏離的位置。如果你打算做任何編程,這是一個重要的工具。進一步閱讀:** [如何調試小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/)** – NathanOliver
此代碼是正確的只是傳遞參數爲例如:./command 4 – clockley1