473,804 Members | 3,021 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Debugging at runtime

Hi,
I'm a complete beginner, having written my second program and finally
got it to compile, I've got an error I can't track down occurring at
runtime - basically whatever I do it says Segmentation Fault.
I was wondering if there was any way I could get a slightly more
verbose description of the error so that I could think about sorting it
out.

Someone mentioned to me that the g++ option -DRANGE_CHECKING would
check if i was accessing uninitialised arrays or something at compile
time, but that hasn't helped, Thanks in advance, I'm really at my wits
end!

May 16 '06 #1
12 1719
Cleverbum wrote:
I'm a complete beginner, having written my second program and finally
got it to compile, I've got an error I can't track down occurring at
runtime - basically whatever I do it says Segmentation Fault.


This newsgroup is only qualified to discuss C++ source; not all its various
implementations and tools, including debuggers.

You could post some source here - most seg faults are easy to spot - or you
could post your question about debugging to a g++ newsgroup.

--
Phlip
http://c2.com/cgi/wiki?ZeekLand <-- NOT a blog!!!
May 16 '06 #2
seems the compiler newsgroups are only posted to every couple of days
or so, so I may as well post the code here, been through it a few times
myself and have had no luck in spotting anything untoward:

/* models particle(s) settling under gravity in three dimensions.
also includes inter-particle gravity */

#include <iostream>
#include <math.h>
#include <fstream>
#include <sstream>
#include <string>
#include <time.h>
using namespace std;

const int n = 1; // number of particles
const double G = 6.6742e-11; // universal gravitational constant
const double gravity = 9.81; // freefall acceleration due to gravity
const int max_time =100;
const int timeStep = 1;

struct vec_3d{
double x, y, z;
};

class particle{
// all vectors stored as arrays [0]=x dir [1]=y dir [2]=z dir
private:
double* pos;
double* vel;
double* frc;
double mass;
bool hard;
double rad;
public:
particle(){
srand(time(0));
int randint = 0;
for(int i=0;i<3;i++){
randint = rand()%1000;
pos[i] = randint / 1000.0;
vel[i]=0.0;
frc[i]=0.0;
}
mass=1.0;
rad=1.0;
hard=true;
}

//void move(double*); // speeds supplied as array
//void move(vec_3d); // speeds supplied as vector structure
void move(); // uses speeds saved within particle object

//void accelerate(doub le*); // forces supplied as array
//void accelerate(vec_ 3d); // forces supplied as vector
void accelerate(); // uses forces stored inside particle object

string toString(){
ostringstream os;
os << pos[0] << '\t'
<< pos[1] << '\t'
<< pos[2] << '\t'
<< vel[0] << '\t'
<< vel[1] << '\t'
<< vel[2] << '\t';
return os.str();
} ;

friend void calculate_force s(particle, particle);
friend void single_particle _forces(particl e);
};

main(){
particle* myParticles = new particle[n];
for(int simulation_time =0;simulation_t ime<max_time; simulation_time
+= timeStep){
for(int i=0; i<n; i++){
if(n>1){
for(int j=i+1; j<n; j++){
calculate_force s(myParticles[i], myParticles[j]);
}
}
single_particle _forces(myParti cles[i]);
myParticles[i].accelerate();
myParticles[i].move();
cout << i << myParticles[i].toString();
}
}

}

void particle::move( ){
for(int j=0;j<3;j++){
pos[j] += vel[j] * timeStep;
}
}

void particle::accel erate(){
for(int j=0;j<3;j++){
vel[j] += frc[j] * timeStep;
}
}

void calculate_force s(particle x, particle y){
for(int i=0;i<3;i++){
//Gravitational attraction between the bodies
int mySign; //used to determine direction of force
if(y.pos[i]>x.pos[i]){mySign = -1;} else {mySign = 1;}
x.frc[i] = mySign * G * x.mass * y.mass / (( y.pos[i] - x.pos[i])*(
y.pos[i] - x.pos[i]));
y.frc[i] = -1 * mySign * G * x.mass * y.mass / (( y.pos[i] -
x.pos[i])*( y.pos[i] - x.pos[i]));
}
}
void single_particle _forces(particl e x){
//gravity acts negative on z axis
x.frc[2] -= x.mass * gravity;
}

May 16 '06 #3
Cl*******@hotma il.com wrote:
seems the compiler newsgroups are only posted to every couple of days
or so, so I may as well post the code here, been through it a few
times myself and have had no luck in spotting anything untoward:

[...]

class particle{
// all vectors stored as arrays [0]=x dir [1]=y dir [2]=z dir
private:
double* pos;
double* vel;
double* frc;
double mass;
bool hard;
double rad;
public:
particle(){
srand(time(0));
int randint = 0;
for(int i=0;i<3;i++){
randint = rand()%1000;
pos[i] = randint / 1000.0;
'pos' pointer has never been initialised. You're dereferencing
an uninitialised (invalid) pointer.

vel[i]=0.0;
frc[i]=0.0;
}
mass=1.0;
rad=1.0;
hard=true;
}

[...]
};

main(){
int main(){
[...]


V
--
Please remove capital As from my address when replying by mail
May 16 '06 #4
big words, worked out what they meant though and no longer getting the
segmentation fault, thanks.

May 16 '06 #5

<Cl*******@hotm ail.com> wrote in message
news:11******** **************@ i40g2000cwc.goo glegroups.com.. .
seems the compiler newsgroups are only posted to every couple of days
or so, so I may as well post the code here, been through it a few times
myself and have had no luck in spotting anything untoward:
As Phlip predicted, the problem is easy to spot:

/* models particle(s) settling under gravity in three dimensions.
also includes inter-particle gravity */

#include <iostream>
#include <math.h>
#include <fstream>
#include <sstream>
#include <string>
#include <time.h>
using namespace std;

const int n = 1; // number of particles
const double G = 6.6742e-11; // universal gravitational constant
const double gravity = 9.81; // freefall acceleration due to gravity
const int max_time =100;
const int timeStep = 1;

struct vec_3d{
double x, y, z;
};

class particle{
// all vectors stored as arrays [0]=x dir [1]=y dir [2]=z dir
Why not use std::vectors? Had you done so (and used them correctly),
you would not have been bit by your misunderstandin g about the
difference between arrays and pointers (you should avoid pointers
in C++, there is almost always a better way).

private:
double* pos;
double* vel;
double* frc;
'pos' 'vel' and 'frc' are *not* arrays, they are pointers. Until
you give them valid values (the addresses of memory that belongs
to your program), accessing their values or dereferencing them
will give undefined behavior (on some systems, manifest as
'segmentation faults')

You need to allocate some memory and assign its address to your
pointers. But better yet, use std::vectors instead.
double mass;
bool hard;
double rad;
public:
particle(){
srand(time(0));
int randint = 0;
for(int i=0;i<3;i++){
randint = rand()%1000;
pos[i] = randint / 1000.0;
Here's the first instance of undefined behavior. You're trying
to access memory at address pos+i. But this will be a random,
unpredictable 'value'.
vel[i]=0.0;
frc[i]=0.0;
And again, and again.
}
mass=1.0;
rad=1.0;
hard=true;
}

//void move(double*); // speeds supplied as array
//void move(vec_3d); // speeds supplied as vector structure
void move(); // uses speeds saved within particle object

//void accelerate(doub le*); // forces supplied as array
//void accelerate(vec_ 3d); // forces supplied as vector
void accelerate(); // uses forces stored inside particle object

string toString(){
ostringstream os;
os << pos[0] << '\t'
<< pos[1] << '\t'
<< pos[2] << '\t'
<< vel[0] << '\t'
<< vel[1] << '\t'
<< vel[2] << '\t';
And again, and again ...
return os.str();
} ;

friend void calculate_force s(particle, particle);
friend void single_particle _forces(particl e);
};

main(){
Main is *required* to be declared as returning type 'int'.
This is *not* optional as in the old version of C.
particle* myParticles = new particle[n];
Now here, you're allocating memory for your pointer 'myParticles'
to point to. This is what should have been done above with your
other pointers. (But again, don't; use std::vectors instead.)
for(int simulation_time =0;simulation_t ime<max_time; simulation_time
+= timeStep){
for(int i=0; i<n; i++){
if(n>1){
for(int j=i+1; j<n; j++){
calculate_force s(myParticles[i], myParticles[j]);
}
}
single_particle _forces(myParti cles[i]);
myParticles[i].accelerate();
myParticles[i].move();
cout << i << myParticles[i].toString();
Make sure 'i' and 'j' never exceed the value n-1. Hint: What
is the value of 'n' at this point?
}
}

}

void particle::move( ){
for(int j=0;j<3;j++){
pos[j] += vel[j] * timeStep;
More invalid memory acesses, resulting in undefined behavior.
}
}

void particle::accel erate(){
for(int j=0;j<3;j++){
vel[j] += frc[j] * timeStep;
And more.
}
}

void calculate_force s(particle x, particle y){
for(int i=0;i<3;i++){
//Gravitational attraction between the bodies
int mySign; //used to determine direction of force
if(y.pos[i]>x.pos[i]){mySign = -1;} else {mySign = 1;}
x.frc[i] = mySign * G * x.mass * y.mass / (( y.pos[i] - x.pos[i])*(
y.pos[i] - x.pos[i]));
y.frc[i] = -1 * mySign * G * x.mass * y.mass / (( y.pos[i] -
x.pos[i])*( y.pos[i] - x.pos[i]));
And more.
}
}
void single_particle _forces(particl e x){
//gravity acts negative on z axis
x.frc[2] -= x.mass * gravity;
And more.

}


Recommendation: Start *much* smaller. Test each small piece
as you go, don't add more until what you have works as desired.
That's how professionals do it, and so should you.

And again, exploit the standard library. Use std::vectors instead
of arrays. They do all the memory management for you automatically.

HTH,
-Mike
May 16 '06 #6

<Cl*******@hotm ail.com> wrote in message
news:11******** **************@ y43g2000cwc.goo glegroups.com.. .
big words, worked out what they meant though and no longer getting the
segmentation fault, thanks.


Those might seem 'big words' to you, but they express
very fundamental concepts. You need to become *very*
familiar with those concepts.

Perhaps your C++ book(s) are of poor quality. Which
one(s) are you using? (See the peer reviews at
www.accu.org for recommendations ; including for those
which to avoid).

-Mike
May 16 '06 #7

Cl*******@hotma il.com wrote:
Hi,
I'm a complete beginner, having written my second program and finally
got it to compile, I've got an error I can't track down occurring at
runtime - basically whatever I do it says Segmentation Fault.
I was wondering if there was any way I could get a slightly more
verbose description of the error so that I could think about sorting it
out.

Someone mentioned to me that the g++ option -DRANGE_CHECKING would
check if i was accessing uninitialised arrays or something at compile
time, but that hasn't helped, Thanks in advance, I'm really at my wits
end


Most development environments come with a debugger. Learn to use it.

In environments with g++ it is called gdb and the compiler command line
switch to turn on debugging symbols is -g. Learning to use a debugger
and a profiler are important parts of computer programming and way
beyond the scope of most newsgroups...bu y a book...no, I can't
recommend one...there is a gdb book online somewhere...

May 16 '06 #8
Cl*******@hotma il.com wrote:
seems the compiler newsgroups are only posted to every couple of days
or so, so I may as well post the code here, been through it a few times
myself and have had no luck in spotting anything untoward:
Hi Cleverbum,

BTW I think you need to pass the arguments by refernece in these
functions:

class particle {...
friend void calculate_force s(particle&, particle&);
friend void single_particle _forces(particl e&);
};

If you dont you will get a copy of particles passed into the functions
and your original particles will remain unchanged.

I have been implementing a library dealing with physical quantities and
your code is just the type of example I am looking for to test the code
and improve it.

http://tinyurl.com/7m5l8

Anyway FWIW Below ---^--> is what the code would look like in my pqs
library.
(Please note that I have had to modify the library code from the
version of pqs above, by adding an array operator to the three_d vect
class and also removing the constraint on multiplication/divison of
vectors by scalars to arithmetic types only and added assignment
operators (so it wont compile with the latest released version
pqs_3_1_0) but this is just the type of code that can help me find out
what is missing.

I am wondering if it would be OK to use this as an example in a future
version of the pqs library, with due attribution (to Cleverbum?) of
course? ( Note also the license, which is the only one acceptable to
boost FWIW)

regards
Andy Little

-------------------------------------------
// Copyright Cleverbum 2005
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

/*
models particle(s) settling under gravity in three dimensions.
also includes inter-particle gravity
*/

#include <ctime>
#include <iostream>
#include <boost/shared_array.hp p>
#include <boost/pqs/t1_quantity/types/out/length.hpp>
#include <boost/pqs/t1_quantity/types/out/velocity.hpp>
#include <boost/pqs/t1_quantity/types/out/force.hpp>
#include <boost/pqs/t1_quantity/types/out/mass.hpp>
#include <boost/pqs/t1_quantity/types/out/time.hpp>
#include <boost/pqs/t1_quantity/types/out/acceleration.hp p>
#include <boost/pqs/t1_quantity/constants/gravitational_c onstant.hpp>
#include <boost/pqs/three_d/vect_out.hpp>
#include <boost/pqs/angle/out/angle.hpp>

namespace pqs = boost::pqs;

const int num_particles = 1; // number of particles
const pqs::time_<int> ::s max_time(100);
const pqs::time_<int> ::s timeStep(1);

class particle{
private:

pqs::three_d::v ect<pqs::length ::m> pos;
pqs::three_d::v ect<pqs::veloci ty::m_div_s> vel;
pqs::three_d::v ect<pqs::force: :N> frc;
pqs::mass::kg mass;
bool hard;
// not referenced?
// pqs::angle::rad rad;
public:
particle()
// note frc and vel are default initialised to 0,0,0 in pqs
:mass(1.0)/*,rad(1.0)*/,hard(true)
{
srand(time(0));
pos.x = pqs::length::mm (rand()%1000);
pos.y = pqs::length::mm (rand()%1000);
pos.z = pqs::length::mm (rand()%1000);
}

void move(); // uses speeds saved within particle object

void accelerate(); // uses forces stored inside particle object

std::string toString(){
std::ostringstr eam os;
os << pos.x << '\t'
<< pos.y << '\t'
<< pos.z << '\t'
<< vel.x << '\t'
<< vel.y << '\t'
<< vel.z << '\t';
return os.str();
} ;
friend void calculate_force s(particle&, particle&);
friend void single_particle _forces(particl e&);
};
int main(){

// See http://www.boost.org/libs/smart_ptr/shared_array.htm
// for documentation.
boost::shared_a rray<
particle myParticles(new particle[num_particles]);


for( pqs::time_<int> ::s simulation_time
= pqs::time_<int> ::s(0);
simulation_time < max_time;
simulation_time += timeStep){

for(int i=0; i < num_particles; ++i){
if(num_particle s > 1){
for(int j = i+1; j < num_particles; ++j){
calculate_force s(myParticles[i], myParticles[j]);
}
}
single_particle _forces(myParti cles[i]);
myParticles[i].accelerate();
myParticles[i].move();
std::cout << i << myParticles[i].toString();
}

}
}

void particle::move( ){
this->pos += this->vel * timeStep;
}

void particle::accel erate(){
this->vel += this->frc / this->mass * timeStep;
}

void calculate_force s(particle& x, particle& y){

for(int i = 0;i < 3;++i){
//Gravitational attraction between the bodies
//used to determine direction of force
int mySign =(y.pos[i] > x.pos[i])? -1:1;
x.frc[i] = mySign
* pqs::physics::g ravitational_co nstant::G
* x.mass * y.mass / pqs::pow<2>(y.p os[i] - x.pos[i]);
y.frc[i] = -1 * mySign
* pqs::physics::g ravitational_co nstant::G
* x.mass * y.mass / pqs::pow<2>( y.pos[i] - x.pos[i]);
}
}

void single_particle _forces(particl e& x){
//gravity acts negative on z axis
x.frc.y -= x.mass * pqs::accelerati on::g;
}

May 17 '06 #9
cheers for the spot on the pass by reference, I was wondering why
nothing was really working...
the other couple of things are that at the moment the code only really
models a kind of wierd ghostly particle which has no hard boundary at
all, over enough time they all occupy the same space, at which point
forces become infinite and particles blast off with infinite
velocities.
I'm working on collision detection and other thing associated with hard
spheres at the moment and can keep you up to date if you'd like?

May 18 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
15949
by: Bob Bamberg | last post by:
Hello All, I have been trying without luck to get some information on debugging the Runtime Error R6025 - Pure Virtual Function Call. I am working in C++ and have only one class that is derived from an Abstract class, I do not believe that this class object is causing me my problem. Below is that message I have posted before to other groups. Question:
0
1268
by: Gary Karasik | last post by:
Hi, One of my SBS 2K3 servers is giving the following errors when trying to run certain applications. Some Googling indicates that these are .Net Framework errors. I've tried reapplying .Net Framework Service Pack 1 for Windows Server 2003, but that didn't help. I'm afraid I might need to pay MS on this one, but before I spend $245 of my client's money, I thought I'd take a shot here. Anybody have any ideas about how to track this one...
1
6253
by: Sathiamoorthy | last post by:
I received a runtime error when I was working in MyApp.exe MyApp.exe Common Language Runtime Debugging Services Application has generated an exception that could not be handled. Process ID=0x14 (1300), Thread Id=0xe8(232) Any one help me
5
3650
by: snicks | last post by:
I'm trying to exec a program external to my ASP.NET app using the following code. The external app is a VB.NET application. Dim sPPTOut As String sPPTOut = MDEPDirStr + sID + ".ppt" Dim p As New System.Diagnostics.Process 'p.Start(MDEPDirStr & "macrun.exe", sPPTOut) p.Start("C:\WINDOWS\SYSTEM32\CALC.EXE") 'p.Start("C:\WINDOWS\SYSTEM32\macrun.exe", sPPTOut)
4
7066
by: yinglcs | last post by:
I am trying to debug a C++ program in GDB on linux. I want to dump out the content of the "this" object, Here is what I get: (gdb) print *this $2 = {path = <incomplete type>} My question is why I don't see the content of 'path'? It said '<incomplete type>'. In the code, path is:
5
7802
by: phnimx | last post by:
Hi , We have developed a number of plug-in .NET Library Components that we typically deploy with our various applications by installing them into the GAC. Each of the applications contains an app.config file referencing arbitrary versions of the plug-in components they wish to consume. Here's the problem: Assuming I have installed any one of our application software,
0
1005
by: TC | last post by:
When I'm debugging code and a runtime error occurs, Visual Studio usually gives me a specific error message and identifies the line which caused the error. Sometimes, however, it does not do those things. Instead, it gives me the generic error message "Exception has been thrown by the target of an invocation" and identifies a line higher up in the call stack. When this happens, it can be difficult to diagnose the cause of the runtime...
0
379
by: stimpy_cm | last post by:
Hi everyone, I’m not a programmer but have a little notion about how things work. I recently downloaded an emulator for my calculator (Texas Instruments Voyage 200), the program uses a library created for .Net framework 1.0 and 1.1. I also activated the compatibility mode for Windows XP SP2 (Which it was the OS the programs were created for). By the way I’ve an HP Pavillion with Intel Core 2 Duo 2.0Ghz processor, and my OS is Windows Vista...
3
2776
by: Rick | last post by:
We have a web site that was built as an ASP.Net Web Site, I am unable to remote debug, when build ing the web site there is not a dll or PDB file generated. I can debug on my local machine but unable to attach to the process when running from the web server. Can someone tell me how to remote debug an ASP.Net Website that does not genate a dll or PDB file? Thanks in advance! Rick
0
2416
by: =?Utf-8?B?QWxoYW1icmEgRWlkb3MgRGVzYXJyb2xsbw==?= | last post by:
Hi misters, i have application winforms in VB.NET When I press F5, for executing Debug....it's slows... I see,
0
10583
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10337
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10082
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9160
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6854
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5654
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4301
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3822
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2995
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.