Segmentation fault on linux

Sorry that I am new to linux, I don't know how can I fix the Segmentation fault. I will be very grateful if anyone can help me.



#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;

}


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);

}
}
Last edited on
Make sure argc >= 2 before calling atoi(argv[1]).
hi
this error may occur when you pass an NULL argument to function in Linux gcc Compiler.
try to check every parameters before passing them to functions.
try this structure :
if (arg1 == NULL ){
printf("arg1 is NULL");
}
functiontest(arg1);

I change some of your code, transform it to C, add examine it with simple example
may be helpful for you

Esmaeel E


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
/*
 * source_00.c
 * 
 * Copyright 2017 ss <ss@ss-system>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 * 
 * 
 * use in linux terminal:
 *  
 * 1.	$ gcc -o source_00 source_00.c -lpthread
 * 2.	$ ./source_00 3
 * 3.	         ls
 * 		 time
 * 		 gcc -version
 */


/*
 * 
 * Include necessary library
 * 
 *
 * 
 */

#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>

#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;
//track the number of times we have run the dispatch funciton
int runtime=1; 

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;


/*
 * 
 * name: dispatch
 * @param: void
 * @return: void
 * 
 */
void dispatch(void){
	row = runtime / 6;
	sleep(1); //wait 1 second to generate column number
	col = runtime % 6 - 1;
	if (runtime % 6 == 0)
	col = 5;
}

/*
 * 
 * name: enqueue
 * @param: character c   
 * @return: void
 * 
 */
void enqueue(char c){
	queue[tail] = c;
	tail = (tail+1)%MAX ;
}

/*
 * 
 * name: dequeue
 * @param: void
 * @return: character temp 
 * 
 */
char dequeue(){
	char temp = queue[head];
	head = (head+1)%MAX ;
	return temp;
}



/*
 * 
 * name: qcTask
 * @param: void * args   
 * @return: void
 * description: 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);
}

/*
 * 
 * name: main
 * @param: int argc, char* argv[]
 * @return: int, no return value
 * description: program entry piont
 */
int main (int argc, char* argv[])
{
	//printf("This\n");
	
	if(argv[1] == NULL){
		printf("argv is NULL!\n");
	}
	printf("Enter some linux terminal command: \n");
	int input = atoi(argv[1]);/// converts string to integer
	//printf( "This\n");

	if(argc!=2 || input == 0 || input>36){
		printf("Input is illegal!\n");
	}
	else{
		pthread_t threads[input];
		//printf( "This\n");

		int rc, i, count = 0;

		srand(time(NULL));
		//printf( "This\n");
		for(i=0;i<input;i++){
			rc = pthread_create(&threads[i], NULL, qcTask, NULL);
			if (rc){
				printf("Error:unable to create thread%d\n",rc);	
				//cout << "Error:unable to create thread," << rc << endl;
				exit(-1);
			}
		}
		//printf( "This\n");
		for (i = 0; i < input; i++){
			//printf( "This p\n");
			rc = pthread_join(threads[i], NULL);
			
			if (rc){
			printf( "Error:unable to join,%d\n",rc);
			exit(-1);
			}
		}

		//initize matrix with default value 'i'
		//printf( "This\n");
		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++){
				printf( "%d",matrix[i][j]);
				if (matrix[i][j] == 'U'){
					count++;
				}
			}
			printf("\n");
		}

		printf("products are unqualified.\n");
		pthread_exit(NULL);
		}
		/// not reach to this piont
		printf( "End of Program Execution\n");
}




1
2
3
4
5
6
7
 * use in linux terminal:
 *  
 * 1.	$ gcc -o source_00 source_00.c -lpthread
 * 2.	$ ./source_00 3
 * 3.	ls
 *     time
 * 	gcc -version




ss@ss-system:~/Desktop/C_Programming/sw_dev$ ./source_00 3
Enter some linux terminal command: 
ls
dir
time
gcc --version
818181000
000000
000000
000000
000000
000000
products are unqualified.
ss@ss-system:~/Desktop/C_Programming/sw_dev$ ls
source_00  source_00.c
ss@ss-system:~/Desktop/C_Programming/sw_dev$ dir
source_00  source_00.c
ss@ss-system:~/Desktop/C_Programming/sw_dev$ time

real	0m0.000s
user	0m0.000s
sys	0m0.000s
ss@ss-system:~/Desktop/C_Programming/sw_dev$ gcc --version
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE
* use in linux terminal:
*
* 1. $ gcc -o source_00 source_00.c -lpthread


Set warnings to a high level:

gcc -std=c11 -Wall -Wextra -pedantic-errrors -o source_00 source_00.c -lpthread


In function 'void enqueue(char)':
86:12: warning: array subscript has type 'char' [-Wchar-subscripts]
In function 'char dequeue()':
98:24: warning: array subscript has type 'char' [-Wchar-subscripts]
At global scope: 112:20: warning: unused parameter 'args' [-Wunused-parameter]


Those warnings come about because of this line (53):

char queue[MAX], head=0, tail=0;

The way to avoid that warning is to always declare one variable per line:

1
2
3
char queue[MAX];
unsigned int head = 0;
unsigned int tail = 0;


The problem with char as a subscript is that it may be implemented as unsigned or signed char. So signed char is obviously a problem there.

I read somewhere (ISO CPP ?) that it is a good idea to compile C programs with a C++ compiler because they are better at handling types.
Hi TheIdeasMan, thanks for improving my answer. can you please explain to me why compiling with c++ is better for type handling?
eec wrote:
can you please explain to me why compiling with c++ is better for type handling?


Not sure exactly, IIRC they didn't say. Unfortunately I don't remember where I read that, so I probably should not have mentioned it.

Edit: I found it ...

https://isocpp.org/wiki/faq/mixing-c-and-cpp

BTW there is another way to handle this whole thing: compile all your code (even your C-style code) using a C++ compiler. That pretty much eliminates the need to mix C and C++, plus it will cause you to be more careful (and possibly —hopefully!— discover some bugs) in your C-style code. The down-side is that you’ll need to update your C-style code in certain ways, basically because the C++ compiler is more careful/picky than your C compiler. The point is that the effort required to clean up your C-style code may be less than the effort required to mix C and C++, and as a bonus you get cleaned up C-style code. Obviously you don’t have much of a choice if you’re not able to alter your C-style code (e.g., if it’s from a third-party).


The underlined part is here:
https://isocpp.org/wiki/faq/big-picture#back-compat-with-c
Last edited on
thanks a lot, great answer.
but accidentally you have a typo in

gcc -std=c11 -Wall -Wextra -pedantic-errrors -o source_00 source_00.c -lpthread

must be
gcc -std=c11 -Wall -Wextra -pedantic-errors -o source_00 source_00.c -lpthread

for more information on Segmentation Faults read Good Alex Allain website

http://www.cprogramming.com/debugging/segfaults.html
One thing to add to that article: In C++11 and later use nullptr, rather than NULL. nullptr was invented to fix the problems associated with using NULL with pointers.
Ending the program with pthread_exit(NULL); isn't right.
As a new I recommend taking some courses on the web as they can really useful and save you a lot of troubles. It's really important to know how to deal with errors and detect them quickly. If you're having troubles doing that on your own you can always use a program as help. I tend to use checkmarx and it works fine.
Good luck!
Ben.
Topic archived. No new replies allowed.