segmentation fault that goes away by using iostream - c++

So this is gnarly. I have a piece of code that used the Columbia Physics System c++ library. I get a segfault when I run it, most probably because the classes: CgArg, and vector f_field_in, etc are uninitialised. I used Valgrind and found that indeed the various arguments were pointing to invalid memory.
The strange this is that if I insert an iostream call anywhere in the two functions, the segfault goes away. I found out when I put flags in places to debug. It also doesn't segfault if I define an integer and write a simple cin >>. That's why I think it's something to do with iostream.
If you know of any reason why a call to iostream would somehow give pieces of code to the arguments, I'd be very thankful if you shared it with me.
#include <iostream>
using namespace std;
#include <config.h>
#include <util/lattice.h>
#include <util/dirac_op.h>
#include <util/gjp.h>
#include <interface.h>
#define CLOVER_MAT_SIZE 72
USING_NAMESPACE_CPS
// Same function for clover matrix and its inverse.
static
void interface(double *h_quda_clover, double *h_cps_clover)
{
h_quda_clover[0]=h_cps_clover[0]; // c00_00_re = C0.x, A0
...and lots more of this stuff...
h_quda_clover[35+36]=h_cps_clover[34+36]; // c32_31_im = C8.w, A5
}
static
void fill_h_clover_inv(Lattice &lat, int site[], double *h_quda_clover_inv_site)
{
double h_cps_clover_inv[72];
Vector *f_field_out, *f_field_in;
CgArg *arg;
CnvFrmType convert=CNV_FRM_NO;
DiracOpClover dirac(lat,f_field_out,f_field_in,arg,convert);
//cout << "B: " << site << endl;
//cout << "B: site: " << site[0] << ' ' << site[1] << ' ' << site[2] << ' ' << site[3] << endl;
dirac.SiteCloverMat(site,h_cps_clover_inv);
interface(h_quda_clover_inv_site,h_cps_clover_inv);
}
void fill_h_clover_inv_all(Lattice &lat, double *h_quda_clover_inv, int parity)
{
double *ptr=h_quda_clover_inv;
int nsites[4];
nsites[0]=GJP.XnodeSites();
nsites[1]=GJP.YnodeSites();
nsites[2]=GJP.ZnodeSites();
nsites[3]=GJP.TnodeSites();
int site[4];
cout << "A: " << site << endl;
for (site[3] = 0; site[3] < nsites[3]; ++(site[3])) {
for (site[2] = 0; site[2] < nsites[2]; ++(site[2])) {
for (site[1] = 0; site[1] < nsites[1]; ++(site[1])) {
site[0] = (site[3] + site[2] + site[1] + parity)%2;
for (; site[0] < nsites[0]; site[0] += 2) {
//cout << "A: site: " << site[0] << ' ' << site[1] << ' ' << site[2] << ' ' << site[3] << endl;
fill_h_clover_inv(lat,site,ptr);
ptr += CLOVER_MAT_SIZE;
}
}
}
}
}

The problem was with some uninitialised arguments being passed to DiracOpClover. Once we initialised CgArg properly,
CgArg cg_arg;
cg_arg.mass=1.0
everything was hunky dory!!
Thank for the help everyone.

Related

Need to create function to optimise and make more efficient

I've written this code that writes coordinates to a text file. I then use excel to plot these coordinates and it creates a rectangle with circles in it.
It works completing fine, but I want to optimize it. I thought I could optimize it by creating another function that has the syntax for the coordinates so I can call the function rather than writing it out every time and repeating the code. However, I am not sure how to do this, I have tried but its not working so some help would be really appreciated.
#include <iostream>
#include <fstream>
#include <math.h>
using namespace std;
#define PI 3.14159265
//this is the function i am trying to create
double coordinate_syntax(double x_coordinate, double y_coordinate){
return map << x_coordinate << ' ' << y_coordinate << endl;
}
int build_environment_map(){
double x0[5]={0.8, 0.8, 1.7, 2.2, 2.25};
double y0[5]={1.5, 2.25, 1.0, 1.3, 0.25};
double r=0.125, wallLength=2.5;
double RD=PI /180;
ofstream map;
map.open("EnvironmentMap.txt");
// The following code is to create a charger based on its centre.
for (int i=0; i<360; i=i+20) {
map << x0[4] + r*cos(i*RD) << ' ' << y0[4] + r*sin(i*RD) << endl;
//coordinate_syntax( x0[4] + r*cos(i*RD), y0[4] + r*sin(i*RD) );
}
for (int i=0; i<360; i=i+10) {
map << x0[0] + r*cos(i*RD) << ' ' << y0[0] + r*sin(i*RD) << endl;
//coordinate_syntax(x0[0]+ r*cos(i*RD), y0[0]+ r*sin(i*RD));
}
for (double j=0 ; j<wallLength; j=j+0.01){
map << j << ' ' << 0 << endl;
//coordinate_syntax(j,0);
}
for (double x=0.3; x<0.55; x=x+0.01){
map << x << ' ' << 0.3 << endl;
//coordinate_syntax(x, 0.3);
}
map.close();
return 0;
}
int main(int argc, char **argv){
int i;
//calling the function
i = build_environment_map();
return 0;
}

CPP Guessing Game not working, its stops after i enter the name

I'm trying to make this kina guess game on C++, I'm a beginner and still learning.
What I'm trying to achieve is a guessing game of two const names, is very simple without errors but it's not working after I enter something. it should report until I find the correct name. Please also I don't want to change the structure of the code, just find why isn't working.
#include <iostream>
#include <string>
using namespace std;
struct Vlerat {
string guess01 = "Resul";
string guess02 = "Rejan";
int numruesi = 0;
};
int main() {
Vlerat funksioni;
string nameGuess;
int nameOkay = 0;
cout << "Gjej njerin prej dy emrava te fshehura." << endl;
cout << "Ndihm: Fillojn me Shkronjen 'R', dhe pas asaj vjen edhe nje shkronj 'e'" << endl;
do {
cout << "Shkruaj Emrin > "; cin >> nameGuess;
if (nameGuess == funksioni.guess01){
cout << "Ju e keni gjetur emrin e njerit nga personat duke provuar gjithesej:";
cout << funksioni.numruesi++ << " here." << endl;
nameOkay++;
}
if (nameGuess == funksioni.guess02) {
cout << "Ju e keni gjetur emrin e njerit nga personat duke provuar gjithesej:";
cout << funksioni.numruesi++ << " here." << endl;
nameOkay++;
}
funksioni.numruesi++;
} while(nameOkay = 0);
}
You should change while(nameOkay = 0); to while(nameOkay == 0);.
Because = is an assignment, but == is operator of comparing (equality)
Read about it here
And here

Pointer to const variables in C++

I am just playing around to see where my current understanding of C++ behaviour ends. I wrote the following code, and got some very unexpected results.
#include <iostream>
#include <cstddef>
using namespace std;
int main()
{
const char c = 'A';
cout << c << endl;
size_t l = (size_t)(&c);
char* d = (char*)l;
*d = 'B';
cout << (size_t)d << " " << (size_t)&c << endl;
cout << *d << " " << c << endl;
}
The first line outputs 'A', as expected. On the second line, the two addresses are the same. However, the third line outputs "B A".
Obviously this is terrible code, but why didn't the value of c change (or why didn't it fail to compile?) In other words, if they both have the same address, why don't they have the same value?
My system is GCC 4.8.1 64-bit on MS Windows 7, x86, if it matters.

Need Help to understand the do while loop in details

Please do not try to modify the code. This code works fine.I took it from a book.I just need some help to understand the behavior of the code.
#include <iostream>
#include <ctime>
using namespace std;
void suffle2(int[][13]);
int main(){
int deck[4][13] = { 0 };
srand(time(0));
suffle2(deck);
return 0;
}
void suffle2(int d[4][13])
{
int row, column;
for (int card = 1; card <= 20; card++)
{
do{
row = rand() % 4;
column = rand() % 13;
cout << "d[" << row << "]" << "[" << column << "]" << "=" << d[row][column]<<endl;
} while (d[row][column] != 0);
d[row][column] = card;
cout << "d[" << row << "]" << "[" << column << "]" << "=" << d[row][column] <<endl;
}
}
Both cout << "d[" << row << "]" << "[" << column << "]" << "=" << d[row][column] <<endl;
I code to understand the behavior.My question is:
deck[4][13] has initialized to 0.So the while loop should not work cause it should always
find d[row][column] == 0 but it is not..it is working fine.
second question is,suppose the output is following:
d[0][4]=0
d[0][4]=1
d[2][4]=0
d[2][4]=2
d[1][12]=0
d[1][12]=3--------duplicate
d[3][11]=0
d[3][11]=4
d[0][6]=0
d[0][6]=5
d[1][12]=3--------duplicate
d[1][11]=0
d[1][11]=6
d[0][7]=0
d[0][7]=7<--------------------duplicate
d[1][6]=0
d[1][6]=8
d[0][6]=5
d[0][11]=0
d[0][11]=9
d[2][11]=0
d[2][11]=10
d[3][11]=4
d[3][2]=0
d[3][2]=11
d[2][11]=10
d[1][10]=0
d[1][10]=12
d[1][6]=8
d[0][9]=0
d[0][9]=13
d[0][1]=0
d[0][1]=14
d[3][4]=0
d[3][4]=15
d[0][7]=7 <---------------------duplicate
d[0][2]=0
d[0][2]=16
d[0][3]=0
d[0][3]=17
d[2][11]=10
d[0][5]=0
d[0][5]=18
d[0][9]=13
d[0][10]=0
d[0][10]=19
d[1][6]=8
d[1][7]=0
d[1][7]=20
Press any key to continue . . .
In the for loop the card value is incremental but when the duplicate card value is found for the same index of array, it is taking the very first value for that index.Why it is not changing the increment value?Please help me to understand the code.
You are right, all values of deck are 0 at the beginning and the loop works because the do{}while(condition); is executing at least once before checking condition. The loop is looking here for the first uninitialized card.
Duplicate output is just what the loop is currently checking, it finds an initialized card so it keeps looking for an uninitialized one (this is the first cout).

Array of Struct

I want to just hard code these values into a table. when I try to use 2D arrays, I run into the problem of dealing with characters and integers. When I do a struct I have this so far but it doesn't divide the information up in columns, and I'm not sure how to format it that way. (I only did 3 rows to start off with, if I get them working, the rest will just be the same)
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
typedef struct table
{
std::string game;
int year;
float rating;
int num_voters;
}t;
void processTab(t*);
int main()
{
t tabl[2] = {0,0};
int i;
processTab(tabl);
for(i=0; i<2; i++)
{
std::cout << "Game: " << setw(20) << tabl[i].game;
std::cout << "\tYear: " << setw(4) << tabl[i].year;
std::cout << "\tRating: " << fixed << setprecision(2) << tabl[i].rating;
std::cout << "\tVoters: " << setw(6) << tabl[i].num_voters;
}
system("pause");
return 0;
}
void processTab(t*tab)
{
(tab[0].game, "twilight struggles");
tab[0].year = 2005;
tab[0].rating = 8.226;
tab[0].num_voters = 10690;
(tab[1].game, "Agricloa");
tab[1].year = 2007;
tab[1].rating = 8.17;
tab[1].num_voters = 23738;
(tab[2].game, "Puerto Rico");
tab[2].year = 2002;
tab[2].rating = 8.163;
tab[2].num_voters = 27433;
}
Table Data:
Game (0) Year (1) Rating (2) Num Voters (3)
Twilight Struggle 2005 8.226 10690
Agricola 2007 8.17 23738
Puerto Rico 2002 8.163 27433
Through the Ages 2006 8.153 8137
Power Grid 2004 8.02 21655
Le Havre 2008 7.972 9258
Eclipse 2011 7.968 3194
Brass 2007 7.911 5814
Dominion: Intrigue 2009 7.895 10889
Caylus 2005 7.878 13878
What I think you are looking for is <iomanip>
#include <iomanip>
std::cout << "Game: " << setw(20) << tabl[i].game;
std::cout << "\tYear: " << setw(4) << tabl[i].year;
std::cout << "\tRating: " << fixed << setprecision(3) << tabl[i].rating;
std::cout << "\tVoters: " << setw(6) << tabl[i].num_voters;
std::cout << std::end;
Notes:
setw adds padding when writing out stuff, so it will always be at least a certain width
setprecision specifies how many decimal places to display
fixed makes floating point never use scientific notation
Your game member is a letter, and you're attemptying to assign it a string. Don't use strcpy in C++, use the std::string class instead.
#include <string>
struct table
{
std::string game;
int year;
double rating;
int num_voters;
};
Avoid using namespace std;, when you get to complex code with many namespaces, those few letters are a small price to pay for avoiding confusion.
Avoid endl: it flushes buffers which is slow. If you just want a newline, use '\n'.
Also, you can use the new initialization syntax to initialize your list:
std::vector<table> tbal = {
{"twilight struggles ", 2005, 8.226, 10690},
{"Agricola ", 2007, 8.17 , 23738},
{"Puerto Rico ", 2002, 8.163, 27433}
};
Short answer: use std::vector, not a raw array.
The following is as close to your original code as I could make it, introducing a minimum number of new features for you:
#include <assert.h> // assert
#include <iostream> // std::cout, std::endl
#include <stddef.h> // ptrdiff_t
#include <string> // std::string
#include <utility> // std::begin, std::end
#include <vector> // std::vector
using namespace std;
typedef ptrdiff_t Size;
template< class Container >
Size countOf( Container& c ) { return end( c ) - begin( c ); }
struct Game
{
string game;
int year;
double rating;
int num_voters;
};
void initialize( vector<Game>& games )
{
assert( countOf( games ) == 0 );
games.resize( 3 );
games[0].game = "twilight struggles";
games[0].year = 2005;
games[0].rating = 8.226;
games[0].num_voters = 10690;
games[1].game = "Agricloa";
games[1].year = 2007;
games[1].rating = 8.17;
games[1].num_voters = 23738;
games[2].game = "Puerto Rico";
games[2].year = 2002;
games[2].rating = 8.163;
games[2].num_voters = 27433;
}
int main()
{
vector<Game> games;
initialize( games );
for( int i = 0; i < countOf( games ); ++i )
{
cout << i << endl;
cout <<"\tGame: " << games[i].game << endl;
cout<<"\tYear: " << games[i].year << endl;
cout<<"\trating: " << games[i].rating << endl;
cout<<"\tnum voters: " << games[i].num_voters << endl;
}
}
There are ways to just declare the data more directly, including brace initializers; check out your C++ textbook.
First you need to define your table (bad name for a struct, by the way) correctly. You're trying to use game to store a string, but have defined it as only a single char. You probably want to change that to a std::string instead.
Then you probably want to do your formatting in an operator<< overloaded to take a reference to table as the type. #MooingDuck has already covered the formatting itself quite well, so it's mostly a matter of how you package that:
std::ostream &operator<<(std::ostream &os, table const &t) {
os << "Game: " << setw(20) << t.game;
os << "\tYear: " << setw(4) << t.year;
os << "\tRating: " << fixed << setprecision(2) << t.rating;
return os << "\tVoters: " << setw(6) << t.num_voters;
}
Along with that, you almost certainly want to change tabl from an array to std::vector<table>:
std::vector<tabl> tabl;
Then processing the table becomes:
std::copy(tabl.begin(), tabl.end(), std::ostream_iterator<table>(std::cout, "\n"));
One other minor detail: you seem to have two entirely different/separate functions, both named processTab. You probably want to rename at least one of those. Just glancing at them, I'd probably call one initializeTable or something on that order.