There is this code in SI, the point is to find the largest sequence of numbers in ascending order in a two-dimensional array using threads (Linux). When compiling everything is fine, but when I run the program, the Segmentation fault (core dumped) error appears
# include & lt; unistd.h & gt;
#include & lt; stdio.h & gt;
#include & lt; pthread.h & gt;
#include & lt; stdlib.h & gt;
#include & lt; sys / types.h & gt;
#include & lt; time.h & gt;
void random1 (int arr [5] [100]) {
int i, j;
for (i = 0; i & lt; 5; i ++)
{
for (j = 0; j & lt; 100; j ++)
{
arr [i] [j] = rand ()% 100;
printf ("% d \ t", arr [i] [j]);
}
printf ("\ n");
}
printf ("\ n");
}
void * thread_func1 (int arr [5] [100]) {
int buffer = 1, maxbuffer = 0, max = 0, minElement = 0, maxElement;
int i, j;
for (i = 0; i & lt; 5; i ++)
{
for (j = 0; j & lt; 100; j ++)
{
if (arr [i] [j + 1] & gt; arr [i] [j])
{
buffer ++;
max = buffer;
if (maxbuffer & lt; max)
{
maxbuffer = max;
maxElement = arr [i] [j + 1];
}
}
if (arr [i] [j + 1] & lt; = arr [i] [j])
{
max = buffer;
if (maxbuffer & lt; max)
{maxbuffer = max;
maxElement = arr [i] [j + 1];
}
buffer = 1;
}
}
minElement = (maxElement + 1) -maxbuffer;
for (i = minElement; i & lt; = maxElement; i ++)
{
printf ("% d \ t", arr [i] [j]);
}
}
}
int main () {
int A [5] [100];
int stime;
stime = time (NULL);
srand (stime);
random1 (A);
pthread_t k1, k2;
pthread_create (& amp; k1, NULL, (void *) thread_func1, (int *) A);
pthread_join (k1, NULL);
printf ("% ld", k1);
exit (0);
}
Another example of implementation of the thread_func1 function, but this error also appears there
void * thread_func1 (int arr [5] [100]) {
int start = 0, lenght = 1, max_start = 0, max_lenght = 0;
int i, j;
for (i = 0; i & lt; 5; i ++) {
for (j = 0; j & lt; 100; j ++) {
for (int k = j + 1; k & lt; 100; k ++)
{
if (arr [i] [j] & lt; arr [i] [k])
lenght ++;
else {
if (lenght & gt; max_lenght)
max_lenght = lenght, max_start = start;
start = k, lenght = 1;
}
}
}
}
for (i = max_start; i & lt; max_start + max_lenght; i ++) {
for (j = max_start; i & lt; max_start + max_lenght; i ++) {
printf ("% p", arr [i] [j]);}}}
Answer 1, authority 100%
You have a corny overflowing the array because of this and you get a Segmentation Fault.
arr [i] [j + 1]
You refer to the element j + 1, while the maximum j = 99, plus one more, we get 100. And since indexing from 0, it turns out that we are referring to an element that does not exist. I think in the loop it is worth changing the condition to j & lt; 99