CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 24
  1. #1
    Join Date
    Feb 2007
    Posts
    112

    Strange Error. Have you seen this before?

    Hi All,

    I have noticed that sometimes when I introduce a new variable to a header file, the code produces following error:
    Code:
    Program received signal SIGSEGV, Segmentation fault.
    0xb7eb3e4e in std::string::assign () from /usr/lib/libstdc++.so.6
    This time, the varibale I introduced was just an int.
    After that, to know where my program crashed, I introduce few "cout" statements in the code. When I found out after which line my code is crashing, I introduce few more "cout" statements. I keep on introducing "cout" statements until the end of the program flow. After that, the code just start working normally with the new introduce variable.

    Do you guys have any idea, why this happens?

    Thanks.

  2. #2
    Join Date
    Feb 2007
    Posts
    112

    Re: Strange Error. Have you seen this before?

    I reproduced the error and found out one more thing.
    When I introduce new variable then I need to change all the "cpp" files a little bit (as I introduced "cout" in my files) , so that they can compile again.
    I think something may be wrong in my Makefile.
    Following is my make file, can you guys see if it is all right?
    Code:
    EXEC	= main
    
    CC	= g++ -g -O2 -Wall
    
    CSRC 	= main.cpp Eulerian.cpp Util.cpp advectPar.cpp Random.cpp Dispersion.cpp 
    
    COBJS   = $(CSRC:.cpp=.o)
    
    
    $(EXEC): $(COBJS)
    	$(CC) -o $(EXEC) $(COBJS)  
    
    %.o : %.cpp
    	$(CC)  -c $<
    
    clean:
    	rm -f $(EXEC) *.o
    Thanks.

  3. #3
    Join Date
    May 2003
    Location
    San Antonio TX
    Posts
    380

    Re: Strange Error. Have you seen this before?

    Quote Originally Posted by pipa
    ...
    I keep on introducing "cout" statements until the end of the program flow. After that, the code just start working normally with the new introduce variable.
    ...
    I have often seen memory problems *seem* to disappear after a few printf statements were added to help track down the problem.

    I assume that adding the printf (cout in your case) cause the memory layout to differ slightly between builds and result in the error occurring at different locations at runtime.

    Please post your code (.h and .cpp).
    John 3:16
    For God so loved the world ...

  4. #4
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Strange Error. Have you seen this before?

    Quote Originally Posted by pipa
    When I found out after which line my code is crashing, I introduce few more "cout" statements. I keep on introducing "cout" statements until the end of the program flow. After that, the code just start working normally with the new introduce variable.
    Remove those "cout" statements and fix the bug.

    All you're doing when you introduce those cout statements is move the bug somewhere else -- you aren't solving any problems, only making them worse (those cout statements are now hiding the bug).

    You have a memory corruption or overwrite problem somewhere in your code. The worse thing you can do is *not* produce the error -- you should be glad that the code gave you a seg fault, so that you can work on it to really fix it, instead of the bug being hidden from you.

    Regards,

    Paul McKenzie
    Last edited by Paul McKenzie; June 17th, 2008 at 06:55 PM.

  5. #5
    Join Date
    Feb 2007
    Posts
    112

    Re: Strange Error. Have you seen this before?

    Thanks Paul and kenrus for ur quick replies.

    It is really a very annoying problem. I rechecked my code again and again....but was not able to find anything wrong in it. Can you guys take a quick look at it?
    here is my code (I posted this code before too, but I made few new changes):

    main.cpp
    Code:
    #include <iostream>
    #include "Dispersion.h"
    void advectPar(const util&,dispersion&,const eulerian&, const char*);
    
    int main(int argc, char *argv[]){
      
      if(argc<2){
        std::cout<<std::endl;
        std::cerr<<"ERROR 1: Method Missing"<<std::endl;
        return 1;
      }
      if(argc>2){
        std::cout<<std::endl;
        std::cerr<<"ERROR 2: Not an appropriate Method, use - old or new"<<std::endl;
        return 2;
        
      }
      if(std::strcmp(argv[1],"old")!=0 && std::strcmp(argv[1],"new")!=0){
        std::cout<<std::endl;
        std::cerr<<"ERROR 3: Not an appropriate Method, use - old or new"<<std::endl;
        return 3;
        
      }
      
      std::cout<<std::endl;
    
      util utl;
      utl.readInputFile();
      
      eulerian eul;
    
      eul.createEul(utl);
      
      dispersion disp;
      disp.createDisp(eul);  
      
      advectPar(utl,disp,eul,argv[1]);
      
      return 0;
    }
    Util.h
    Code:
    #ifndef UTIL_H
    #define UTIL_H
    
    #include <string>
    class util{
    public:
    	util();
    	void readInputFile();
    	int twidth,numPar, nx,ny,nz, theight, windFieldData;
    	double timeStep,ustar,dur,sCBoxTime,eCBoxTime, avgTime,numBox,zSrc,rSrc,zBoxSize,zo;
    	double bnds[6];
    	std::string file,src;
    private:
    	int profile;
    	std::string outFile;
    };
    #endif
    Util.cpp
    Code:
    #include <fstream>
    #include <iostream>
    #include <sstream>
    #include "Util.h"
    util::util(){
    }
    
    void util::readInputFile(){
      zo=0.1;
      std::ifstream in;
      in.open("input.txt");
      
      char line[1024];
      std::string inputStr;
      
      while(!in.eof()){
        in.getline(line,3600000);
    
        if(line[0]!='#' && strlen(line)!=0){
          std::istringstream str(line);
          str >> inputStr;
    
          if(inputStr=="twidth"){
    	str >> twidth;
          }
          if(inputStr=="theight"){
    	str >> theight;
    	numPar=twidth*theight;
          }
          if(inputStr=="nx"){
    	str >> nx;
          }
          if(inputStr=="ny"){
    	str >> ny;
          }
          if(inputStr=="nz"){
    	str >> nz;
          }
          if(inputStr=="windFieldData"){
    	str >> windFieldData;
          }
          if(inputStr=="time_step"){
    	str >> timeStep;
          }
          if(inputStr=="output_file"){
    	str >> file;
          }
          if(inputStr=="duration"){
    	str >> dur;
          }
          if(inputStr=="ustar"){
    	str >> ustar;
          }
          if(inputStr=="startCBoxTime"){
    	str >> sCBoxTime;
          }
          if(inputStr=="endCBoxTime"){
    	str >> eCBoxTime;
          }
          if(inputStr=="averagingTime"){
    	str >> avgTime;
          }
          if(inputStr=="bounds"){
    	//str >> lBnd;
    	//str >> uBnd;
    	for(int i=0;i<2;i++)
    	  str>>bnds[i];
    	for(int i=2;i<6;i++)
    	  bnds[i]=0.0;	
          }
          if(inputStr=="numBox_z"){
    	str >> numBox;
    	zBoxSize=(bnds[1]-bnds[0])/numBox;
          }
          if(inputStr=="source_info"){
    	str >> src;
    	str >> zSrc;
    	str >> rSrc;
          }
          inputStr="";
        }
      }
    }
    Eulerian.h
    Code:
    #ifndef EULERIAN_H
    #define EULERIAN_H
    
    #include "Util.h"
    #include <fstream>
    #include <string>
    #include <vector>
    
    class eulerian{
    	
    public:
      typedef struct{
        float u;
        float v;
        float w;
      }wind;	
      std::vector<wind> windVec;
      std::vector<wind> sigma; 
      
    
      std::vector<double> eps,tau33,lam33,tau33dz;
      util utl;  
      void createEul(const util&);
    
     private:
      int windField;
      std::vector<double> zInMeters; 
      double zo;
      
      void createWindField();
      void createSigmaAndEps();
      void createTausAndLamdas();
      void createTauGrads();
      void writeWindsAndSigma();
      void createA1Matrix();
      
      void uniform();
      void shear();
      
    };
    #endif
    Eulerian.cpp
    Code:
    #include <iostream>
    #include <math.h>
    #include "Eulerian.h"
    
    
    void eulerian::createEul(const util& u){
      utl=u;
      zo=utl.zo;
      windField=utl.windFieldData;
      zInMeters.resize(utl.nz,0.0);
    
      for(int i=0;i<utl.nz;i++){
        std::cout<<i<<std::endl;
        zInMeters.at(i)=i+0.5;
      }
      createWindField();
    
    }
    
    void eulerian::createWindField(){
      switch(windField){
      case 3:
        uniform();
        break;
      case 4:
        shear();
        break;
      case 10:
        uniform();
        break;
      default:
        std::cerr<<"NO WIND Field Specified"<<std::endl;
        exit(1);
      }
    }
    
    void eulerian::uniform(){
      
      windVec.resize(utl.nz);
      for(int i=0;i<utl.nz; i++)
        windVec.at(i).w=3.0;
      createSigmaAndEps();
    }
    void eulerian::shear(){
      windVec.resize(utl.nz);
      double Wh= 3.0;//Change in sigma function too if you change values here
      double Zh=10.0;
     
      for(int i=0;i<utl.nz; i++){
        windVec.at(i).w=Wh*( log((zInMeters.at(i))/zo) / log(Zh/zo) );
      }
      createSigmaAndEps();
    }
    void eulerian::createSigmaAndEps(){
      sigma.resize(utl.nz);
      eps.resize(utl.nz);
      switch(windField){
        
      case 3:
        for(int i=0; i<utl.nz;i++){
          sigma.at(i).w = utl.ustar * 1.3;
          eps.at(i)=pow(utl.ustar,3.0) / (0.4*utl.nz/2.0);
        }
        break;
      case 4:
        for(int i=0; i<utl.nz;i++){
          double ustarEul=0.4*windVec.at(i).w/ (log(zInMeters.at(i)/zo));
          sigma.at(i).w = 1.3 * ustarEul * pow( ( 1.0-( zInMeters.at(i)/(utl.nz) ) ), 3.0/4.0);
          eps.at(i)=pow(ustarEul,3.0) / (0.4*zInMeters.at(i));
        }
        break;
      case 10:
        {
          double ustarEul=0.0;
          for(int i=0; i<utl.nz;i++){
    	if(i<utl.nz/2)
    	  ustarEul=0.44;
    	else
    	  ustarEul=0.44;
    	sigma.at(i).w = 1.3*ustarEul;
    	eps.at(i)=pow(ustarEul,3.0) / (0.4*zInMeters.at(i));
          }
        }
        break;
        
      default:
        std::cerr<<"Cannot Create Sigmas"<<std::endl;
      }
      writeWindsAndSigma();
      createTausAndLamdas();
    }
    
    void eulerian::createTausAndLamdas(){
      tau33.resize(utl.nz);
      lam33.resize(utl.nz);
    
      for(int i=0;i<utl.nz;i++){
        tau33.at(i)=(sigma.at(i).w * sigma.at(i).w);
        lam33.at(i)=(1/tau33.at(i));
      }
      createTauGrads();
    }
    
    void eulerian::createTauGrads(){
      tau33dz.resize(utl.nz);  
      tau33dz.at(0)=( -2.0*(tau33.at(0)/(0.5*log(0.5/zo))) );
    
      std::cout<<"Looks Too High: "<<tau33dz.at(0)<<std::endl;
      
      for(int i=1;i<(utl.nz)-1;i++){
        double grad=(tau33.at(i+1)-tau33.at(i-1))/2.0;
        tau33dz.at(i)=grad;
      }
      tau33dz.at((utl.nz)-1)=tau33dz.at(utl.nz-2);
    }
    
    void eulerian::createA1Matrix(){
    /*Still working on*/
    }
    
    
    
    void eulerian::writeWindsAndSigma(){
      std::ofstream winds,sigmas;
      winds.open("windfield.dat");
      sigmas.open("sigma.dat");
      if(!winds.is_open()){
        std::cerr<<"Windfield File Open ERROR"<<std::endl;
        exit(1);
      }
      if(!sigmas.is_open()){
        std::cerr<<"Sigma File Open ERROR"<<std::endl;
        exit(1);
      }
    
      for(int i=0; i<utl.nz;++i){
        winds<<zInMeters.at(i)<<"  "<<windVec.at(i).w<<std::endl;
        sigmas<<zInMeters.at(i)<<"  "<<sigma.at(i).w<<std::endl;
      }
      
    }
    Dispersion.h
    Code:
    #ifndef DISPERSION_H
    #define DISPERSION_H
    
    #include <list>
    #include <vector>
    #include <iostream>
    #include "Eulerian.h"
    #include "Random.h"
    class dispersion{
     public:
      eulerian eul;
      void createDisp(const eulerian&);
      std::list<double> zIniPos;
      std::list<double> wPrime;
      double eps;
      int numTimeStep;
      std::vector<double> timeStepStamp,tStrt;
      
     private:
      
      double zSrc;
      int numPar;
    	
    };
    #endif
    Dispersion.cpp
    Code:
    #include "Dispersion.h"
    #include <fstream>
    #define EPSILON 0.00001
    void dispersion::createDisp(const eulerian& e){
    
      eul=e;
      zSrc=eul.utl.zSrc;
      numPar=eul.utl.theight*eul.utl.twidth;
      numTimeStep=ceil(eul.utl.dur/eul.utl.timeStep);
      timeStepStamp.resize(numTimeStep);
      double dt=eul.utl.timeStep;
      
      for(int i=0;i<numTimeStep;++i)
        timeStepStamp.at(i)=i*dt+dt;
      
      double dur=eul.utl.dur;
      
      zIniPos.resize(numPar,zSrc);  
      tStrt.resize(numPar);
      
      /*particles released per time step
        (integer-as number of particles cannot be a fraction)*/
      
      int parPerTimestep=numPar*dt/dur; 
                                       
      std::cout<<"Emitting "<<parPerTimestep<< " particles per Time Step"<<std::endl;
    
      int parRel=0; //number of particles released in a particluar time step
      double startTime=dt;
    
      for(int i=0;i<numPar;i++){
        /*when number of particles to be released in a particluar time step reaches total 
          number of particles to be released in that time step, then increase the start time 
          by timestep and set parRel=0*/
    
    
        if(parRel==parPerTimestep){
          startTime=startTime+dt;
          parRel=0;
        }
        
        tStrt.at(i)=startTime;
        double rann=random::norRan();
        wPrime.push_back(eul.sigma.at((int)zSrc).w * rann);
        ++parRel;
      }
      /*
        Checking if the start ing time for the last particle is equal to the duration of
        the simulation (for continous release ONLY)
      */
      if (fabs(tStrt.back()-dur)>EPSILON){
        std::cerr<<" Error, in start time of the particles"<<std::endl;
        exit(1);
      }
    }
    advectPar.cpp
    Code:
    #include <iostream>
    #include <fstream>
    #include <vector>
    #include "Dispersion.h"
    #include <omp.h>
    
    void average(const int);
    void outputConc();
    
    int numPar,nz,numBox,tStep;
    double zBoxSize,lBndz,uBndz,dt,avgTime;
    std::vector<double> cBox,tStrt,timeStepStamp,zBoxCen;
    std::list<double>zPos,wPrimeCopy;
    std::ofstream output;
    
    void advectPar(const util &utl, dispersion &disp, const eulerian &eul, const char* model){
      random::random();
      const char*  method=model;
      std::cout<<"Inside advect"<<std::endl;
      
      std::list<double>::iterator itPos,itwPrime;
    
      numPar=utl.numPar; 
      nz=utl.nz;
      numBox=utl.numBox;
    
      zBoxSize = utl.zBoxSize;	  
      lBndz=utl.bnds[0];
      uBndz=utl.bnds[1];
    
      zBoxCen.resize(numBox);
      zBoxCen.at(0)=lBndz+(zBoxSize/2.0);
      for(int i=1;i<numBox;++i)
        zBoxCen.at(i)=zBoxCen.at(i-1)+zBoxSize;
      
      
      dt=utl.timeStep;
      avgTime=utl.avgTime;
      
      if(std::strcmp(method,"old")==0){
        if(remove("output_old.dat")!=0)
          perror("Output File Delete error");
        else
          std::cout<<" OLD - Output File succesfully removed!!"<<std::endl;
        output.open("output_old.dat");
      }
      else if(std::strcmp(method,"new")==0){
        if(remove("output_new.dat")!=0)
          perror("Output File Delete error");
        else
          std::cout<<" NEW - Output File succesfully removed!!"<<std::endl;
        
        output.open("output_new.dat");
      }
      
      if(!output.is_open()){
        std::cerr<<"Output.dat file open error"<<std::endl;
        exit(1);
      }
    
      double sCBoxTime=utl.sCBoxTime;
      int numTimeStep=disp.numTimeStep;
    
      tStrt.resize(numPar);
      tStrt=disp.tStrt;
    
      timeStepStamp.resize(numTimeStep);
      timeStepStamp=disp.timeStepStamp;
    
      zPos.resize(numPar);
      zPos=disp.zIniPos;
    
      cBox.resize(numBox,0.0);
    
      std::ofstream outPrimes;
      if(std::strcmp(method,"old")==0)
        outPrimes.open("Primes_old.dat");
      else if(std::strcmp(method,"new")==0)
        outPrimes.open("Primes_new.dat");
      
      if(!outPrimes.is_open()){
        std::cerr<<"Prime output file not open"<<std::endl;
        exit(1);
      }  
    
      //For every time step
      for(tStep=0; tStep<numTimeStep; tStep++){
        itwPrime=disp.wPrime.begin();
        itPos=zPos.begin();
        //Move each particle for every time step
        
        int par=0;
        for(itPos=zPos.begin();itPos!=zPos.end();++itPos,++itwPrime){
          
          if(*itPos>=0 && *itPos<nz && tStrt.at(par)<=timeStepStamp.at(tStep)){ 
    	/*if the partice is in domain and ready to be released*/
    	double wPrime=*itwPrime; //Get previous fluctuating component
    	
    	//Get other relevant Eulerian quantities
    	double CoEps=5.7*eul.eps.at(int(*itPos));
    	double lam33=eul.lam33.at(int(*itPos));
    	double tau33dz=eul.tau33dz.at(int(*itPos));
    	//Get Random Number
    	double ran=random::norRan();
    
    	double wMean=eul.windVec.at((int)*itPos).w;
    
    	if(std::strcmp(method,"old")==0){
    	  if(tStep==0)std::cout<<"Method is: "<<method<<std::endl;
    	  double dwMem =-0.5*CoEps*lam33*wPrime*dt + 0.5*tau33dz*dt;
    	  double dwDrft =0.5*wMean*tau33dz*lam33*wPrime*dt + 0.5*tau33dz*lam33*wPrime*wPrime*dt;
    	  double dwRan = ran*(sqrt(CoEps*dt));
    
    	  double dw = dwMem + dwDrft + dwRan ;
    	  wPrime=*itwPrime+dw;
    	}
    	else if(std::strcmp(method,"new")==0){
    	  if(tStep==0)std::cout<<"Method is: "<<method<<std::endl;
    	  
    	  double lambda=-0.5*CoEps*lam33 + 0.5*wMean*lam33*tau33dz;
    	  double k=0.5*tau33dz;
    	  //First Step
    	  double wMem=wPrime*exp(lambda*dt);
    	  double wDri=-(k/lambda)*(1-exp(lambda*dt));
    	  double wRan= ran*sqrt( (CoEps/(2.0*lambda))  * (exp(2.0*lambda*dt)-1.0)   );
    	  double wPrime_1st =wMem + wDri+ wRan;
    	  double g=0.5*lam33*tau33dz;
    	  double wPrime_2nd=wPrime_1st/(1-(g*wPrime_1st*dt));
    	  wPrime=wPrime_2nd;
    	}
    	*itwPrime=wPrime;
    	*itPos=*itPos + wMean*dt + (*itwPrime)*dt;
    	/*	if(par==1){
    	  std::cout<<"   "<<tStep<<"    "<<*itPos<<"   "<< CoEps<<std::endl;
    	  getchar();
    	  }*/
    
          }
          ++par;
        }
        
        if(timeStepStamp.at(tStep) >= sCBoxTime)			
          average(tStep);
        if(timeStepStamp.at(tStep)>= sCBoxTime+avgTime){
          outputConc();
          avgTime=avgTime+utl.avgTime;
        }
      }
    }
    
    void average(const int tStep){
      std::list<double>::iterator itPos;
      itPos=zPos.begin();
      for(int i=0;i<numPar;i++){
        if(*itPos>=0 && *itPos<nz && tStrt.at(i)<=timeStepStamp.at(tStep)){
          if(*itPos >=lBndz && *itPos<=uBndz){
    	int idz =((int)((*itPos - lBndz) / zBoxSize));
    	cBox.at(idz)=cBox.at(idz)+1;
          }
        }
        itPos++;
      }
    }
    void outputConc(){
      std::cout<<"output"<<std::endl;
      std::cout<<"Time:  "<<tStep<<std::endl;
      for(int i=0;i<numBox;i++){		
        
        //    std::cout<<"concentration: "<<zBoxCen.at(i)<<"    "<<cBox[i]/avgTime<<"     "<<cBox[i]<<std::endl;
        output<<zBoxCen.at(i)<<"   "<<cBox[i]/avgTime<<"     "<<cBox[i]<<std::endl;
      }
      for(int i=0; i<numBox;i++)
        cBox.at(i)=0.0;
    }
    Input File {input.txt}
    Code:
    #Number of particles(twidth*theight)
    twidth  1000
    theight 10
    
    #Set the Domain
    nx 100
    ny 50
    nz 20
    
    #Use value of 3 for uniform in U direction
    #Use value of 4 for the varied in U direction
    #Use value of 10 for Special case of uniform flow and varying sigma in U direction
    windFieldData 4
    
    time_step .01
    
    #output file for the values of the collection boxes
    output_file data.txt
    
    #Total time in seconds to run simulation
    #set to 0 to let user decide when to quit
    duration 100
    
    #Ustar value for prime and lambda calculations
    ustar 0.084
    
    #Collection box start Time
    startCBoxTime 10.0
    
    #Collection box end Time
    endCBoxTime 10000.0
    
    #Collection box averaging Time
    averagingTime 90.0
    
    #Collection box bounds; lower_x,upper_x
    bounds 0.0 20.0 
    
    #Collection box discretization
    
    #number of boxes in z direction 
    numBox_z   20
    
    source_info point 0 0.05
    Random.h
    Code:
    #ifndef RANDOM_H
    #define RANDOM_H
    
    #include <cstdlib>
    #include <math.h>
    
    class random{
    public:
    	random();
    	static double uniRan();
    	static double norRan();
    private:
    	static bool m_normal_value;
    	static double m_remaining_value;
    
    };
    #endif
    Random.cpp
    Code:
    #include "Random.h"
    #include <iostream>
    
    random::random(){
      m_normal_value=false;
      //  std::cout<<"Set  RANDOM seed "<<std::endl;
      std::srand(1);
    }
    
    double random::uniRan(){
      return std::rand()/(double)RAND_MAX;
    }
    
    double random::norRan(){
      float rsq, v1, v2;
      if (m_normal_value == false){
        do{
          v1 = 2.0f * uniRan() - 1.0f;
          v2 = 2.0f * uniRan() - 1.0f;
          rsq = v1*v1 + v2*v2;
        } while (rsq >= 1.0);
        
        rsq = sqrt( (-2.0f * log(rsq) ) / rsq );
        
        m_remaining_value = v2 * rsq;
        m_normal_value = true;
        
        return v1*rsq;
      }
      else{
        m_normal_value = false;
        return m_remaining_value;
      }
    }
    bool random:: m_normal_value;
    double random::m_remaining_value;
    Last edited by pipa; June 18th, 2008 at 03:04 PM.

  6. #6
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Strange Error. Have you seen this before?

    Have you used your debugger to help solve the problem? You really can't write all of this code without knowing how to use the debugger if you have problems.

    Regards,

    Paul McKenzie

  7. #7
    Join Date
    Feb 2007
    Posts
    112

    Re: Strange Error. Have you seen this before?

    Thanks paul.

    Yeah I run my code in debugging mode. I use gdb debugger. I have little or no experience with gdb.
    In the present version of the code, the code crashes at Eulerian.cpp at the following line:
    Code:
     for(int i=0;i<20;i++){
        std::cout<<i<<std::endl;
        zInMeters.at(i)=i+0.5;
      }
    zInMeters is a vector of doubles.
    Can you see if I am treating this vector correctly?

    Thanks.
    Last edited by pipa; June 17th, 2008 at 08:25 PM.

  8. #8
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Strange Error. Have you seen this before?

    Quote Originally Posted by pipa
    In the present version of the code, the code crashes at Eulerian.cpp at the following line:
    Code:
     for(int i=0;i<20;i++){
        std::cout<<i<<std::endl;
        zInMeters.at(i)=i+0.5;
      }
    The at() throws an exception if the index is out of bounds. What is the value of i, and how many items are really in zInMeters (zInMeters.size())? Don't guess or assume what these values are -- actually display these values, either using gdb or using cout.

    Regards,

    Paul McKenzie

  9. #9
    Join Date
    Feb 2007
    Posts
    112

    Re: Strange Error. Have you seen this before?

    When I do the following:

    Code:
    std::cout<<"Size:"<<"  "<<zInMeters.size()<<std::endl;
      for(int i=0;i<20;i++){
        std::cout<<"i:"<<"  "<<i<<std::endl;
        zInMeters.at(i)=i+0.5;
      }
    I get the following output:
    Code:
    Size:  20
    i:  0
    
    Program received signal SIGSEGV, Segmentation fault.
    0x0804b7d6 in eulerian::createEul (this=0xbf818b7c, u=@0xbf818c70) at Eulerian.cpp:16
    That is, the loop terminates at the very first instance of accessing zInMeters vector. Can you see any reason why does this happen?

    This is the output of "back trace" from gdb:
    Code:
    #0  0x0804b7d6 in eulerian::createEul (this=0xbf818b7c, u=@0xbf818c70) at Eulerian.cpp:16
    #1  0x08049c6e in main (argc=Cannot access memory at address 0x0
    ) at main.cpp:35
    Last edited by pipa; June 17th, 2008 at 08:51 PM.

  10. #10
    Join Date
    Apr 1999
    Posts
    27,449

    Re: Strange Error. Have you seen this before?

    Code:
    char line[1024];
      std::string inputStr;
      
      while(!in.eof()){
        in.getline(line,3600000);
    Why is line declared as 1024 characters, but your getline expects 3,600,000 characters to be placed in line?

    Replace the reading of the file with hard-coded data. Does the code run as expected? If it does, then the problem is the reading of the data.

    Second, you create instances of util, eulerian, etc., but they contain uninitialized members. You should initialize all of your class members when creating instances of them.

    For example:
    Code:
    #include <string>
    class util{
    public:
    	util();
    	void readInputFile();
    	int twidth,numPar, nx,ny,nz, theight, windFieldData;
    	double timeStep,ustar,dur,sCBoxTime,eCBoxTime, avgTime,numBox,zSrc,rSrc,zBoxSize,zo;
    	double bnds[6];
    	std::string file,src;
    private:
    	int profile;
    	std::string outFile;
    };
    //..
    #include <algorithm>
    
    util::util() : profile(0), timeStep(0.0), ustar(0.0), dur(0.0), 
                      sCBoxTime(0), eCBoxTime(0), avgTime(0), 
                      numBox(0), zSrc(0), rSrc(0), zBoxSize(0), zo(0),
                      twidth(0), numPar(0), nx(0), ny(0), nz(0), theight(0),
                      windFieldData(0)
    {
         std::fill(bnds, bnds+6, 0.0);
    }
    This guarantees that any util object has members initialized to some value.

    Regards,

    Paul McKenzie

  11. #11
    Join Date
    Feb 2007
    Posts
    112

    Re: Strange Error. Have you seen this before?

    Quote Originally Posted by Paul McKenzie
    Code:
    char line[1024];
      std::string inputStr;
      
      while(!in.eof()){
        in.getline(line,3600000);
    Why is line declared as 1024 characters, but your getline expects 3,600,000 characters to be placed in line?
    That is just one of my trials. I forgot to change that ....I was just trying out different things. I will change that.

    Quote Originally Posted by Paul McKenzie
    Replace the reading of the file with hard-coded data.
    I will do that to check the output.

    Quote Originally Posted by Paul McKenzie
    Does the code run as expected? If it does, then the problem is the reading of the data.
    When the code runs fine, then it does what it expected from the code. I will hardcore the data and see if reading data is the problem.

    Quote Originally Posted by Paul McKenzie
    Second, you create instances of util, eulerian, etc., but they contain uninitialized members. You should initialize all of your class members when creating instances of them.
    I will do that.

    Thanks a lot Paul for helping me out.

  12. #12
    Join Date
    Feb 2007
    Posts
    112

    Re: Strange Error. Have you seen this before?

    I made the above suggested changes but I am still getting the problem.

    I hardwired all my input data into the file and initialized all the varibales present in the Util and Eulerian class by the default constructor.

    When I first hardwired the input data, I got an error and the cout statement of "zInMeters.size()" was showing me "0", even though I have 20 as an input. After that, I just introduced another "cout" statement to make sure that "util.nz" [as I do zInmeters.resize(utl.nz,0.0)] has the value which i mentioned hardwired (i.e. 20). The code started to run fine when i used "cout" for displaying "utl.nz" .

    This is very very starnge and annoying at the same time.
    I dont know where I messed up.
    Please help.

  13. #13
    Join Date
    May 2002
    Location
    Lindenhurst, NY
    Posts
    867

    Re: Strange Error. Have you seen this before?

    This may or may not be your problem, but I think you posted something about changing a header file, then things not working...maybe when you change your header file your build environment does not correctly figure out which dependent .cpp files need to be re-compiled, so one .cpp file has a definition of a struct with 3 fields & the other has a definition with 4 fields (for example). As a sanity check...rebuild your entire project after making a change to a .h file...might help, might not. To force it, remove all the object files (.o or .obj) before rebuilding. I'm thinking maybe when you start adding the couts it is forcing the re-compile & that is fixing the problem. Point is, if this is the case, its easy enough to figure out--just rebuild the entire project by removing all object files.

  14. #14
    Join Date
    May 2002
    Location
    Lindenhurst, NY
    Posts
    867

    Re: Strange Error. Have you seen this before?

    Quote Originally Posted by pipa
    I reproduced the error and found out one more thing.
    When I introduce new variable then I need to change all the "cpp" files a little bit (as I introduced "cout" in my files) , so that they can compile again.
    I think something may be wrong in my Makefile.
    Following is my make file, can you guys see if it is all right?
    Code:
    EXEC	= main
    
    CC	= g++ -g -O2 -Wall
    
    CSRC 	= main.cpp Eulerian.cpp Util.cpp advectPar.cpp Random.cpp Dispersion.cpp 
    
    COBJS   = $(CSRC:.cpp=.o)
    
    
    $(EXEC): $(COBJS)
    	$(CC) -o $(EXEC) $(COBJS)  
    
    %.o : %.cpp
    	$(CC)  -c $<
    
    clean:
    	rm -f $(EXEC) *.o
    Thanks.

    I could be mistaken, but shouldn't you make your %.o be dependent on %.cpp and %.h? Its been a while since I played with makefiles so I could be wrong.

  15. #15
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,725

    Re: Strange Error. Have you seen this before?

    one problem:

    in class eulerian ... you set the zInMeters vector to all zeros, but
    in shear() you take the log of each element in the vector.

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured