little problem with segmentation fault

#include <pthread.h>
...
for (;;) //till breake
{
...
pthread_t threads[3];
done[1] = false;
done[2] = false;
done[3] = false;
pthread_create(&threads[2], NULL, run2, (void *)2);
pthread_create(&threads[1], NULL, run1, (void *)1);
pthread_create(&threads[3], NULL, run3, (void *)3);
...
}
...
void *run1(void *threadid)
{
int midT = mid-1;
int m[n];
for (int i = 1; i <= n; i++)
{
int w = 0;
for (int j = 1; j <= n; j++)
{
if (graph[i][j] == 1) w++;
}
m[i] = w;
}
int k = 0;
for (int i = 1; i <= n; i++)
{
if (m[i] >= midT)
{
k++;
s[1][k] = i;
}
}
ic[1] = select(k, midT+1, 1);
done[1] = true;
}
//------------------------------------------------------------------------------
void *run2(void *threadid)
{
int midT = mid;
int m[n];
for (int i = 1; i <= n; i++)
{
int w = 0;
for (int j = 1; j <= n; j++)
{
if (graph[i][j] == 1) w++;
}
m[i] = w;
}
int k = 0;
for (int i = 1; i <= n; i++)
{
if (m[i] >= midT)
{
k++;
s[2][k] = i;
}
}
ic[2] = select(k, midT+1, 2);
done[2] = true;
}
//------------------------------------------------------------------------------
void *run3(void *threadid)
{
int midT = mid+1;
int m[n];
for (int i = 1; i <= n; i++)
{
int w = 0;
for (int j = 1; j <= n; j++)
{
if (graph[i][j] == 1) w++;
}
m[i] = w;
}
int k = 0;
for (int i = 1; i <= n; i++)
{
if (m[i] >= midT)
{
k++;
s[3][k] = i;
}
}
ic[3] = select(k, midT+1, 3);
done[3] = true;
}

In the most cases I get segmentation fault.. Maybe someone can help me?
Last edited on
Could you repost your code with the # button (http://www.cplusplus.com/forum/articles/1624/) ?
It makes it much easier to read.
One thing I have noticed is your are declaring

pthread_t threads[3];

and then referencing the 4th element

pthread_create(&threads[3], NULL, run3, (void *)3);

For pthread_t threads[3];

you can only reference

1
2
3
threads[0]
threads[1]
threads[2]


Indexes always start at zero
Yea I know that indexes starts at zero, but I've noticed that if I have array for example of 3 elements and I index it 1, 2, 3 always everything is ok. So I index my arrays from 1 because it's much easyer to understand.
Then you will have to create an array of one more than you actually need. The compiler will let you do
1
2
3
threads[3];

x = thread[3];

If you read index 3 and your program doesn't crash you're very lucky. The contents of that memory could be anything, Doing this will guarantee your program to be unpredictable, crash and generally be unstable.
Yea you were right, that was a problem. Thanx for help!
Topic archived. No new replies allowed.