C++ Code segmentation fault only in vscode - c++

My C++ code (shown below) works on this site:
GDB Online but not in Visual Studio, where it crashes at
iterations[imag_times][real_times] = i % (iter / 2);
when imag_times is 1 and real_times is 0 with the exception being Exception has occurred. Segmentation fault
I have installed GDB version 7.6.1.
My Question: Does anybody know how to fix that and why this is happening?
#include <iostream>
using namespace std;
int main()
{
// initialization
const double real_min = -1;
const double real_max = 1;
const double imag_min = -1;
const double imag_max = 1;
const int iter = 30;
const double real_offs = 0.01;
const double imag_offs = 0.01;
double z_real = 0;
double z_imag = 0;
double c_real = real_min;
double c_imag = imag_max;
int real_times = 0;
int imag_times = 0;
int** iterations = new int*[1];
iterations[0] = new int;
int i = 0;
// start
while(c_imag >= imag_min)
{
iterations = (int**)realloc(iterations, sizeof(int*) * (imag_times + 1));
real_times = 0;
c_real = real_min;
while(c_real <= real_max)
{
iterations[imag_times] = (int*)realloc(iterations[imag_times], sizeof(int) * (real_times + 1));
z_real = 0;
z_imag = 0;
for(i = 0; i < iter; i++)
{
double z_imag2 = z_imag * z_imag;
z_imag = 2 * z_real * z_imag + c_imag;
z_real = z_real * z_real - z_imag2 + c_real;
if(z_real * z_real + z_imag * z_imag > 4)
{
break;
}
}
iterations[imag_times][real_times] = i % (iter / 2);
real_times++;
c_real = real_min + real_offs * real_times;
}
imag_times++;
c_imag = imag_max - imag_offs * imag_times;
}
// output
for(int i = 0; i < imag_times; i++)
{
for(int j = 0; j < real_times; j++)
{
cout << iterations[i][j];
cout << ",";
}
cout << "\n";
}
cout << "done";
std::cin.get(); // pause so the program doesnt exit instantly
return 0;
}
Thanks in advance!

Related

Gradient descent converging towards the wrong value

I'm trying to implement a gradient descent algorithm in C++. Here's the code I have so far :
#include <iostream>
double X[] {163,169,158,158,161,172,156,161,154,145};
double Y[] {52, 68, 49, 73, 71, 99, 50, 82, 56, 46 };
double m, p;
int n = sizeof(X)/sizeof(X[0]);
int main(void) {
double alpha = 0.00004; // 0.00007;
m = (Y[1] - Y[0]) / (X[1] - X[0]);
p = Y[0] - m * X[0];
for (int i = 1; i <= 8; i++) {
gradientStep(alpha);
}
return 0;
}
double Loss_function(void) {
double res = 0;
double tmp;
for (int i = 0; i < n; i++) {
tmp = Y[i] - m * X[i] - p;
res += tmp * tmp;
}
return res / 2.0 / (double)n;
}
void gradientStep(double alpha) {
double pg = 0, mg = 0;
for (int i = 0; i < n; i++) {
pg += Y[i] - m * X[i] - p;
mg += X[i] * (Y[i] - m * X[i] - p);
}
p += alpha * pg / n;
m += alpha * mg / n;
}
This code converges towards m = 2.79822, p = -382.666, and an error of 102.88. But if I use my calculator to find out the correct linear regression model, I find that the correct values of m and p should respectively be 1.601 and -191.1.
I also noticed that the algorithm won't converge for alpha > 0.00007, which seems quite low, and the value of p barely changes during the 8 iterations (or even after 2000 iterations).
What's wrong with my code?
Here's a good overview of the algorithm I'm trying to implement. The values of theta0 and theta1 are called p and m in my program.
Other implementation in python
More about the algorithm
This link gives a comprehensive view of the algorithm; it turns out I was following a completely wrong approach.
The following code does not work properly (and I have no plans to work on it further), but should put on track anyone who's confronted to the same problem as me :
#include <vector>
#include <iostream>
typedef std::vector<double> vect;
std::vector<double> y, omega(2, 0), omega2(2, 0);;
std::vector<std::vector<double>> X;
int n = 10;
int main(void) {
/* Initialize x so that each members contains (1, x_i) */
/* Initialize x so that each members contains y_i */
double alpha = 0.00001;
display();
for (int i = 1; i <= 8; i++) {
gradientStep(alpha);
display();
}
return 0;
}
double f_function(const std::vector<double> &x) {
double c;
for (unsigned int i = 0; i < omega.size(); i++) {
c += omega[i] * x[i];
}
return c;
}
void gradientStep(double alpha) {
for (int i = 0; i < n; i++) {
for (unsigned int j = 0; j < X[0].size(); j++) {
omega2[j] -= alpha/(double)n * (f_function(X[i]) - y[i]) * X[i][j];
}
}
omega = omega2;
}
void display(void) {
double res = 0, tmp = 0;
for (int i = 0; i < n; i++) {
tmp = y[i] - f_function(X[i]);
res += tmp * tmp; // Loss functionn
}
std::cout << "omega = ";
for (unsigned int i = 0; i < omega.size(); i++) {
std::cout << "[" << omega[i] << "] ";
}
std::cout << "\tError : " << res * .5/(double)n << std::endl;
}

How to implement midpoint displacement

I'm trying to implement procedural generation in my game. I want to really grasp and understand all of the algorithms nessecary rather than simply copying/pasting existing code. In order to do this I've attempted to implement 1D midpoint displacement on my own. I've used the information here to write and guide my code. Below is my completed code, it doesn't throw an error but that results don't appear correct.
srand(time(NULL));
const int lineLength = 65;
float range = 1.0;
float displacedLine[lineLength];
for (int i = 0; i < lineLength; i++)
{
displacedLine[i] = 0.0;
}
for (int p = 0; p < 100; p++)
{
int segments = 1;
for (int i = 0; i < (lineLength / pow(2, 2)); i++)
{
int segs = segments;
for (int j = 0; j < segs; j++)
{
int x = floor(lineLength / segs);
int start = (j * x) + 1;
int end = start + x;
if (i == 0)
{
end--;
}
float lo = -range;
float hi = +range;
float change = lo + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (hi - lo)));
int center = ((end - start) / 2) + start;
displacedLine[center - 1] += change;
segments++;
}
range /= 2;
}
}
Where exactly have I made mistakes and how might I correct them?
I'm getting results like this:
But I was expecting results like this:
The answer is very simple and by the way I'm impressed you managed to debug all the potential off-by-one errors in your code. The following line is wrong:
displacedLine[center - 1] += change;
You correctly compute the center index and change amount but you missed that the change should be applied to the midpoint in terms of height. That is:
displacedLine[center - 1] = (displacedLine[start] + displacedLine[end]) / 2;
displacedLine[center - 1] += change;
I'm sure you get the idea.
The problem seems to be that you are changing only the midpoint of each line segment, rather than changing the rest of the line segment in proportion to its distance from each end to the midpoint. The following code appears to give you something more like what you're looking for:
#include <iostream>
#include <cstdlib>
#include <math.h>
#include <algorithm>
using namespace std;
void displaceMidPt (float dline[], int len, float disp) {
int midPt = len/2;
float fmidPt = float(midPt);
for (int i = 1; i <= midPt; i++) {
float ptDisp = disp * float(i)/fmidPt;
dline[i] += ptDisp;
dline[len-i] += ptDisp;
}
}
void displace (float displacedLine[], int lineLength, float range) {
for (int p = 0; p < 100; p++) {
int segs = pow(p, 2);
for (int j = 0; j < segs; j++) {
float lo = -range;
float hi = +range;
float change = lo + static_cast <float> (rand()) / (static_cast <float> (RAND_MAX / (hi - lo)));
int start = int(float(j)/float(segs)*float(lineLength));
int end = int(float(j+1)/float(segs)*float(lineLength));
displaceMidPt (displacedLine+start,end-start,change);
}
range /= 2;
}
}
void plot1D (float x[], int len, int ht = 10) {
float minX = *min_element(x,x+len);
float maxX = *max_element(x,x+len);
int xi[len];
for (int i = 0; i < len; i++) {
xi[i] = int(ht*(x[i] - minX)/(maxX - minX) + 0.5);
}
char s[len+1];
s[len] = '\0';
for (int j = ht; j >= 0; j--) {
for (int i = 0; i < len; i++) {
if (xi[i] == j) {
s[i] = '*';
} else {
s[i] = ' ';
}
}
cout << s << endl;
}
}
int main () {
srand(time(NULL));
const int lineLength = 65;
float range = 1.0;
float displacedLine[lineLength];
for (int i = 0; i < lineLength; i++) {
displacedLine[i] = 0.0;
}
displace (displacedLine,lineLength,range);
plot1D (displacedLine,lineLength);
return 0;
}
When run this way, it produces the following result:
$ c++ -lm displace.cpp
$ ./a
*
* *
* ***
* * * *
* ** **** * **
* *** **** * * * ** *
* * ** ** *** * * * *
** ** *
* * * ***
** ***
*

C++ compilation error: "Double array redeclared as different kind of symbol"

When I try to compile the following code, I get the following errors:
hmm.cpp:16:29: error: ‘double gamma [3000][4]’ redeclared as different kind of symbol
/usr/include/x86_64-linux-gnu/bits/mathcalls.h:266:1: error: previous declaration of >‘double gamma(double)’
hmm.cpp: In function ‘double updateModel(int&, int, int, double, double, int, double*, >double ()[4], double ()[5005], double*)’:
hmm.cpp:67:11: warning: pointer to a function used in arithmetic [-Wpointer-arith]
hmm.cpp:67:14: warning: pointer to a function used in arithmetic [-Wpointer-arith]
hmm.cpp:67:18: error: assignment of function ‘double gamma(double)’
hmm.cpp:67:18: error: cannot convert ‘int’ to ‘double(double)throw ()’ in assignment
hmm.cpp:69:12: warning: pointer to a function used in arithmetic [-Wpointer-arith]
hmm.cpp:69:15: warning: pointer to a function used in arithmetic [-Wpointer-arith]
hmm.cpp:69:46: error: invalid operands of types ‘double(double)throw ()’ and ‘double’ to >binary ‘operator+’
hmm.cpp:69:46: error: in evaluation of ‘operator+=(double(double)throw (), double)’
I get similar errors everytime gamma is used in the code.
Code follows:
#include <iostream>
#include <fstream>
#include <cstring>
#include <cstdlib>
#include <cmath>
//double atof(const char* str)
using namespace std;
#define MAXT 3000
#define MAXSTATE 4
#define MAXRANGE 5005
#define maxString 52
#define maxResult 405
double alpha[MAXT][MAXSTATE];
double beta[MAXT][MAXSTATE];
double gamma [MAXT][MAXSTATE];
double delta[MAXT][MAXSTATE];
double psi[MAXT][MAXSTATE];//Ψ
double xi[MAXT][MAXSTATE][MAXSTATE];
inline int getIndex(const double& value,const double& min,const double&
max,const int& k)
{
int ret;
//ret = int((value - min)*((max-min)/k)); // [possible error 1]
ret = (k - 1)*(value - min) / (max-min);
return ret;
}
// all the matrix start from 1 to max
// oMin is the minimal value of O
double updateModel(int& q,int tWindow, int oRange, double oMin, double oMax, int
stateNum, double _o[MAXT],double _A[MAXSTATE][MAXSTATE],double _B[MAXSTATE][MAXRANGE],double _Pi[MAXSTATE])
{
double p;
/* calculate lambda */
// alpha
for(int s=1;s<=stateNum;s++)
alpha[1][s] = _Pi[s]*_B[s][getIndex(_o[1], oMin, oMax, oRange)];
for(int t=2;t<=tWindow;t++)
{
for(int s=1;s<=stateNum;s++)
{
alpha[t][s] = 0;
for(int j=1;j<=stateNum;j++)
alpha[t][s] += alpha[t-1][j] * _A[j][s] * _B[s][getIndex(_o[t], oMin, oMax, oRange)];
}
}
// p
p = 0;
for(int i=1;i<=stateNum;i++)
p+=alpha[tWindow][i];
//beta
for(int s = 1; s <= stateNum; s++)
beta[tWindow][s] = 1;
for(int t = tWindow - 1; t >= 1; t--)
{
for(int s = 1; s <= stateNum; s++)
{
beta[t][s] = 0;
for(int j=1;j<=stateNum;j++)
beta[t][s] += beta[t + 1][j] * _A[j][s] * _B[s][getIndex(_o[t + 1], oMin, oMax, oRange)];
}
}
//gamma
for (int t = 1; t <= tWindow; t ++){
for (int i = 1; i <= stateNum; i ++){
gamma[t][i] = 0;
for (int s = 1; s <= stateNum; s ++){
gamma[t][i] += (alpha[t][s] * beta[t][s]);
}
gamma[t][i] = alpha[t][i] * beta[t][i] / gamma[t][i];
}
}
//delta, psi
for (int i = 1; i <= stateNum; i ++){
delta[1][i] = _Pi[i] * _B[i][getIndex(_o[1], oMin, oMax, oRange)];
psi[1][i] = 0;
}
for (int t = 2; t <= tWindow; t ++){
for (int i = 1; i <= stateNum; i ++){
int k = 1;
delta[t][1] = delta[t - 1][1] * _A[1][i] * _B[i][getIndex(_o[t], oMin, oMax, oRange)];
for (int j = 2; j <= stateNum; j ++)
{
if ((delta[t - 1][j] * _A[j][i]) > (delta[t - 1][k] *
_A[k][i]) )
{
delta[t][i] = delta[t - 1][j] * _A[j][i] *
_B[i][getIndex(_o[t], oMin, oMax, oRange)];
k = j;
}
}
psi[t][i] = k;
}
}
int k = 1;
double p_star = delta[tWindow][1];
for (int i = 1; i <= stateNum - 1; i ++)
{
if (delta[tWindow][i + 1] > delta[tWindow][k])
{
p_star = delta[tWindow][i + 1];
k = i + 1;
}
}
int q_star = k;
//xi
for (int t = 1; t <= tWindow - 1; t ++)
{
for (int i = 1; i <= stateNum; i ++)
{
for (int j = 1; j <= stateNum; j ++)
{
xi[t][i][j] = 0;
for (int s1 = 1; s1 <= stateNum; s1 ++)
{
for (int s2 = 1; s2 <= stateNum; s2 ++)
{
xi[t][i][j] = xi[t][i][j] + beta[t + 1][s2]
* _B[s2][getIndex(_o[t + 1], oMin, oMax, oRange)] * _A[s1][s2] * alpha [t][s1];
}
}
xi[t][i][j] = beta[t + 1][j] * _B[j][getIndex(_o[t + 1],
oMin, oMax, oRange)] * _A[i][j] * alpha [t][i] / xi[t][i][j];
}
}
}
//update
for (int i = 1; i <= stateNum; i ++)
{
_Pi[i] = gamma[1][i];
for (int j = 1; j <= stateNum; j ++)
{
double numerator = 0;
double denominator = 0;
for (int t = 1; t <= tWindow - 1; t ++)
{
numerator += xi[t][i][j];
denominator += gamma[t][i];
}
_A[i][j] = numerator / denominator;
}
double tmp,detmp;
for(int k=1; k<=oRange; k++)
{
tmp = 0;
detmp = 0;
for(int t=1; t<=tWindow; t++)
{
if(getIndex(_o[t], oMin, oMax, oRange) == k ) tmp+=gamma[t][i];
detmp+=gamma[t][i];
}
_B[i][k] = tmp/detmp;
}
}
q = q_star;
return p;
}
//double _A[maxState][maxState],double _B[maxState][MAXRANGE],double _Pi[maxState]
void converge(int& q, double previousP,double threshold, int tWindow, int
maxRange, double oMin, double oMax, int stateNum, double _o[MAXT],double _A[MAXSTATE][MAXSTATE],double _B[MAXSTATE][MAXRANGE],double _Pi[MAXSTATE])
{
double currentP = updateModel(q, tWindow,maxRange,oMin,oMax,stateNum, _o,
_A,_B,_Pi);
while(fabs(currentP-previousP)>threshold)
{
previousP = currentP;
currentP = updateModel(q, tWindow,maxRange,oMin,oMax,stateNum, _o,
_A,_B,_Pi);
}
}
int main()
{
ifstream fin1("..\\data\\input.txt");
ifstream fin2("..\\data\\input2.txt");
ofstream fout("..\\data\\output.txt");
double result[maxResult];
double _o[MAXT];
double _A[MAXSTATE][MAXSTATE];
double _B[MAXSTATE][MAXRANGE];
double _Pi[MAXSTATE];
int oRange;
int nState;
double oMin;
double oMax;
int tWindow;
/*
#####################################################################
Begin- Input data
*/
string tnum;
char tmps[maxString];
double t;
int cnt1, cnt2;
int cnttmp;
/* Get the num of input1 and input2 */
if(!fin1.eof())
{
getline(fin1,tnum);
strcpy(tmps,tnum.c_str());
t = atof(tmps);
cnt1 = int(t);
}
if(!fin2.eof())
{
getline(fin2,tnum);
strcpy(tmps,tnum.c_str());
t = atof(tmps);
cnt2 = int(t);
}
/* Get the real data of input1 and input2 */
cnttmp = 1;
oMin = oMax = 0;
while(!fin1.eof())
{
getline(fin1,tnum);
strcpy(tmps,tnum.c_str());
t = atof(tmps);
_o[cnttmp++] = t;
if(oMin > t) oMin = t;
if(oMax < t) oMax = t;
// printf("1: %lf\n",t);
}
//printf("oMin = %lf, oMax = %lf\n",oMin, oMax);
while(!fin2.eof())
{
getline(fin2,tnum);
strcpy(tmps,tnum.c_str());
t = atof(tmps);
_o[cnttmp++] = t;
//printf("2: %lf\n",t);
}
/*
End- Input data
#####################################################################
*/
/*
Parameters to set:
int oRange;
int tWindow;
*/
int maxRange = 5000;
tWindow = 70;
nState = 3;
double previousP = 0;
double threshold = 1e-8;
// [To do]
for(int i=1;i<=nState;i++)
for(int j=1;j<=nState;j++)
_A[i][j] = (1.0)/ nState;
for(int i=1;i<=nState;i++)
for(int j=1;j<=maxRange;j++)
_B[i][j] = (1.0)/maxRange;
for(int i=1;i<=nState;i++)
_Pi[i] = (1.0)/nState;
/*
#####################################################################
Begin- Process data
*/
int q_star;
converge(q_star,previousP,threshold, tWindow, maxRange, oMin, oMax, 3,
_o,_A,_B,_Pi);
int bestIndex = 1; // the index of O(T+1)
int tmp;
int choice;
double predictValue,currentValue;
double bestValue;
for(int k=1;k<=cnt2;k++) // cnt2 Real Data
{
currentValue = _o[cnt1+k-1];
bestValue = 0;
for(int i=1;i<=maxRange;i++)
{
//tmp = getIndex(_o[cnt1+k], oMin, oMax, maxRange);
if(_B[q_star][i] > bestValue)
{
bestValue = _B[q_star][i];
bestIndex = i;
}
}
predictValue = oMin + (oMax - oMin) * (bestIndex-1) /(maxRange-1);
//index --> value
converge(q_star,previousP,threshold, tWindow, maxRange, oMin, oMax,
3, _o+k,_A,_B,_Pi);
if(predictValue > currentValue) choice = 1;
else choice = -1;
result[k] = choice * (_o[cnt1+k] - _o[cnt1+k-1]);
}
/*
End- Process data
#####################################################################
*/
/*
#####################################################################
Begin- Output data
*/
for(int i=1;i<=cnt2;i++)
fout << result[i] << endl;
/*
End- Output data
#####################################################################
*/
fin1.close();
fin2.close();
fout.close();
return 0;
}
Could someone tell me how to fix this error?
Thank you.
The error message is pretty clear:
mathcalls.h:266:1: error: previous declaration of >‘double gamma(double)’
There is a function double gamma(double) that you get when importing cmath.
Change the name of your array.
Your variable gamma conflicts with a symbol defined in mathcalls.h, a prototype for the gamma function.

SSE addition producing garbage

I am trying to compare SSE float[4] addition to standard float[4] addition. I tried this:
#include <iostream>
#include <vector>
struct Point4
{
Point4()
{
data[0] = 0;
data[1] = 0;
data[2] = 0;
data[3] = 0;
}
float data[4];
};
static float SumOfDifferences(const Point4& a, const Point4& b)
{
// This function only returns the sum of the sum of the components
float sumValues = 0.0f;
for(unsigned int i = 0; i < 4; ++i)
{
sumValues += a.data[i] + b.data[i];
}
return sumValues;
}
void Standard()
{
Point4 a;
a.data[0] = 1;
a.data[1] = 2;
a.data[2] = 3;
a.data[3] = 4;
Point4 b;
b.data[0] = 1;
b.data[1] = 6;
b.data[2] = 3;
b.data[3] = 5;
float total = 0.0f;
for(unsigned int i = 0; i < 1e6; ++i)
{
total += SumOfDifferences(a, b);
}
std::cout << "total: " << total << std::endl;
}
void Vectorized()
{
typedef int v4sf __attribute__ (( vector_size(4*sizeof(float)) ));
v4sf a;
float* aPointer = (float*)&a;
aPointer[0] = 1; aPointer[1] = 2; aPointer[2] = 3; aPointer[3] = 4;
v4sf b;
float* bPointer = (float*)&b;
bPointer[0] = 1; bPointer[1] = 2; bPointer[2] = 3; bPointer[3] = 4;
float total = 0.0f;
v4sf result;
float* resultPointer = (float*)&result;
for(unsigned int i = 0; i < 1e6; ++i)
{
result = a + b; // Vectorized operation
// Sum the components of the result (this is done with the "total += " in the Standard() loop
for(unsigned int component = 0; component < 4; ++component)
{
total += resultPointer[component];
}
}
std::cout << "total: " << total << std::endl;
}
int main()
{
// Standard();
Vectorized();
return 0;
}
but the output is 'inf' for the Vectorized() function. When I stepped through with a debugger, the values of 'result' seem to be garbage (i'd expect them to be (0, 4, 0, 1) ). Where am I going wrong here?
Try typedef float v4sf __attribute__ (( vector_size(4*sizeof(float)) ));
I get 2e+07 as the result.

mandelbrot image creation using pthread

i am getting an error: invalid lvalue in assignment.
this is the only error with my program, it looks like a fatal compile time error regards on specially pthread.
i am trying to get the inputs in the runtime, using command line arguments, that's why i am getting an error, but previously i didn't get any error, when i run the program in static input initialized in the program itself.
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <sched.h>
#include <sys/types.h>
#include <math.h>
#include <time.h>
#include <sys/time.h>
#include <stdint.h>
#define num_threads 8
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
unsigned int width = 1500;
unsigned int height = 1500;
unsigned int max_iterations = 30000;
unsigned int **color = NULL;
double min_re;
double max_re;
double min_im;
double max_im;
double x_factor;
double y_factor;
unsigned int NUM_OF_THREADS;
int chunk = 10;
int total_sum = 0;
bool file_write()
{
FILE *fractal = fopen("mandelbrot_imagepthread.ppm","w+");
if(fractal != NULL)
{
fprintf(fractal,"P6\n");
fprintf(fractal,"# %s\n", "Mandelbrot_imagepthread.ppm");
fprintf(fractal,"%d %d\n", height, width);
fprintf(fractal,"255\n");
int y = 0, x = 0;
unsigned int R = 0, G = 0, B = 0;
for(x = 0; x < width; ++x)
{
for(y = 0; y < height; ++y)
{
R = (color[y][x]*10)%255;
G = 255-((color[y][x]*10)%255);
B = ((color[y][x]*10)-150)%255;
if(R == 10) R = 11;
if(G == 10) G = 11;
if(B == 10) B = 11;
putc(R, fractal);
putc(G, fractal);
putc(B, fractal);
}
}
fclose(fractal);
}
return true;
}
int method(int x, int y, int max_iterations, double max_im,double min_re,double x_factor, double y_factor)
{
double c_im = max_im - y*y_factor;
double c_re = min_re + x*x_factor;
double Z_re = c_re, Z_im = c_im;
unsigned int col = 0;
for(unsigned n=0; n<max_iterations; ++n)
{
double Z_re2 = Z_re*Z_re, Z_im2 = Z_im*Z_im;
if(Z_re2 + Z_im2 > 4)
{
col = n;
break;
}
Z_im = 2 * Z_re * Z_im + c_im;
Z_re = Z_re2 - Z_im2 + c_re;
}
return col;
}
void* method1(void* t)
{
double min_re = -2.0;
double max_re = 1.0;
double min_im = -1.2;
double max_im = min_im+(max_re-min_re)*height/width;
double x_factor = (max_re-min_re)/(width-1);
double y_factor = (max_im-min_im)/(height-1);
int x,y;
int sub_total = -1;
pthread_mutex_lock(&mut);
if(total_sum < height)
{
sub_total = total_sum;
total_sum = total_sum + chunk;
}
pthread_mutex_unlock(&mut);
while(sub_total > -1)
{
int start_point = sub_total;
int end_point = start_point + chunk;
for(y=start_point; y<end_point; y++)
{
for(x=0; x<width; ++x)
{
int m1;
uintptr_t m2;
m2 = (uintptr_t)t;
m1 = method(x,y,max_iterations,max_im,min_re,x_factor,y_factor);
if(m1)
{
color[x][y] = m1*40;
}
}
}
sub_total = -1;
pthread_mutex_lock(&mut);
if(total_sum < height)
{
sub_total = total_sum;
total_sum = total_sum + chunk;
}
pthread_mutex_unlock(&mut);
}
pthread_exit((void*)&t);
}
int main(int argc, char *argv[])
{
if(argc != 9)
{
printf("There is an error in the input given.\n");
return 0;
}
else
{
height = atoi(argv[1]);
width = atoi(argv[2]);
max_iterations = atoi(argv[3]);
min_re = atof(argv[4]);
max_re = atof(argv[5]);
min_im = atof(argv[6]);
max_im = atof(argv[7]);
num_threads = atoi(argv[8]);
}
color = (unsigned int**)malloc(height*sizeof(unsigned int*));
x_factor = (max_re-min_re)/(width-1);
y_factor = (max_im-min_im)/(height-1);
printf("height = %d\twidth = %d\tmaximum_iterations = %d\tminimum_x-value = %.2f\tmaximum_x-value = %.2f\tminimum_y-value = %.2f\tmaximum_y-value = %.2f\tno. of threads = %d\t\n",height,width,max_iterations,min_re,max_re,min_im,max_im,num_threads);
int x;
for(x = 0; x < height; x++)
{
color[x] = (unsigned int*)malloc(width*sizeof(unsigned int));
}
time_t ts,te;
time(&ts);
pthread_t t1[num_threads];
pthread_attr_t attr;
int l1;
void *att;
double value = 0.0;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE);
for(int i=0;i<num_threads;i++)
{
l1 = pthread_create(&t1[i], &attr, method1, (void *) i);
if(l1)
{
printf("There is some kind of error in thread creation: %d", l1);
exit(-1);
}
}
pthread_attr_destroy(&attr);
for(int i=0;i<num_threads;i++)
{
l1 = pthread_join(t1[i],&att);
if(l1)
{
printf("There is some kind of error in thread creation: %d", l1);
exit(-1);
}
double result = *(double *)att;
value += result;
}
time(&te);
double diff = difftime(te,ts);
file_write();
printf("Total Time elapsed: %.2f seconds\n",diff);
for(x = 0; x < height; x++)
{
free(color[x]);
}
free(color);
return 0;
pthread_exit(NULL);
}
The error here is that you define num_threads to be 8 with a #define directive instead declaring it as int!
Change #define num_threads 8 to int num_threads=8;
In general you should avoid #define directives because they are evil.
If you want to have a global constant variables declare it as static const rather than a #define. Those directives are substituted by the preprocessor to the following code and lead to the following (non-sense) code.
8 = atoi(argv[8])