Different behavior while debugging than while running - c++

I have problem with running and debugging my program.
The thing is that when I run my program by 'Run' there is some bug, but when I'm trying to debug it, then it works fine.
I don't have a clue how to solve that.
There is link for short video: Video presenting problem
While running 2 sectors don't work, while debugging everything works fine.
I'm using CLion.
I find that different behavior happens in this function(it's only a piece of code, because whole project is quite big):
LevelSegmentCords* Space::findPlaceForBruteForce(int x, int y, int z) {
LevelSegmentCords *segmentCords = nullptr;
int i;
for(i=0;i<this->getHeight();i++){
int lastX=0,lastY=0;
int checkerX=0,checkerY=0;
do{
segmentCords = levels[i].findFreeSector(x,y,lastX,lastY);
if(segmentCords != nullptr){
segmentCords->setStartLevel(i);
for(int j=0;i+j<this->getHeight() && j<=z;j++){
if(!levels[i+j].isSectorFree(segmentCords->getX1(),
segmentCords->getY1(),
segmentCords->getX2()+1,
segmentCords->getY2()+1)){
checkerX = segmentCords->getX1();
checkerY = segmentCords->getY1();
}
}
if(checkerX != lastX || checkerY != lastY){
if(checkerX + 1 < this->x){
lastX = checkerX+1;
lastY = checkerY;
}else{
break;
}
}else{
return segmentCords;
}
}else{
break;
}
}while(true);
}
return nullptr;
}
This function should basically find place to put there cuboid.

Related

Do I need to add some kind of check before continuing when hopping to other void

I'm new(-ish) to C++, and I'm trying to learn something new every day. Today I'm trying to figure this out.
Do I have to check if Valmis == 1 so it won't continue/return before Realtest() is complete?
This is just an example.
int valmis = 0;
void test::Main()
{
//just some basic stuff
do
{
if (!strcmp())
{
//here too
float testing = 0;
printf("Test? 1=do it Else=Nothing\n");
scanf(" %f", &testing);
if (testing == 1)
{
Realtest();
//Realtest needs to be completed before continuing
if (valmis == 1) //Do I need this or does it continue after RealTest() is complete without this?
return (somethingmate = true);
}
else
{
return (somethingmate = true);
}
}
} while();
return (somethingmate = false);
}
void test::Realtest()
{
//doing something here that I need to do before continuing in main/letting somethingmate to become true
valmis = 1; //do i need this?
}

SDL2 Side scrolling variable not accruing

I have a cat game I have been working on in pygame that I am now writing in c++ SDL2 which are similar. But I have a weird specific problem. A variable in my level.cc class doesn't accrue with old += new in the move() function I am thinking that it is being set to 0 somewhere or my scope is off but I am just lost. I will post the files that are pertinent here and then link to my github as well. I appreciate your time and help.
The level.cc file:
void Level::move(int newx){
groundX += newx;
}
and the cat.cc file:
void Cat::move(int screenSize, Level l){
if((catmX + mVelX > 0) && (catmX + mVelX + (catwidth / 2) < (screenSize * .70))){
catmX += mVelX;
} else if(catmX + mVelX + (catwidth / 2) >= (screenSize * .70)){
l.move(CAT_VEL);
catmY += mVelY;
}
}
and the main:
string grndLoc = "src/grass.png";
Level level1(extra.loadTexture(grndLoc, extra.getRen()), extra.getHeight());
string backgroundImage = "src/sky.png";
SDL_Texture *bck = extra.loadTexture(backgroundImage, extra.getRen());
if(bck == nullptr){
extra.destroyer(bck);
extra.quitGame();
return 1;
}
SDL_Event e;
bool quit = false;
while(!quit){
while(SDL_PollEvent(&e)){
if(e.type == SDL_QUIT){
quit = true;
}
switch(e.key.keysym.sym){
case SDLK_ESCAPE:
quit = true;
break;
}
catplayer.handleEvent(e);
}
SDL_RenderClear(extra.getRen());
extra.renderTexture(bck, extra.getRen(), 0, 0, extra.getWidth(), extra.getHeight());
level1.rend(extra);
extra.renderTexture(catplayer.getTexture(), extra.getRen(), catplayer.getX(), catplayer.getY(), catplayer.getclip());
SDL_RenderPresent(extra.getRen());
catplayer.move(extra.getWidth(), level1);
https://github.com/ironsketch/catGamecpp
My teacher made mention that I was probably calling the constructor somewhere! I found that I was passing a copy of the level and not a pointer to the level!
void Cat::move(int screenSize, Level l){
So I changed it to
void Cat::move(int screenSize, Level *l){
I updated a few other things to reflect that I am now using a pointer and it's fixed! Thanks everyone who responded <3

Program crashes without error message

I am using the Qt Creator (Community) to learn how to code.
I have an assignment to calculate the roots of a function, and I tried using the code I found here in a Qt Widgets Project.
When I try to run the program, Qt didn't detect any errors.
However, my program crashes whenever I try to show the results using on_pushButton_clicked().
My lecturer suspects there should be an open loop somewhere but I don't see any.
Any help would be very much appreciated.
Code below:
double function1(double q)
{
double ab = ((q*q*q)+(9*q*q)-(15*q)+98)*(sin(q));
return ab;
}
void MainWindow::on_pushButton_clicked()
{
ui->label->setText(tr("%1").arg(func1()));
}
double MainWindow::func1()
{
std::setprecision(4);
double precision = 0.001;
double a = -10;
double b = -9;
double product = function1(a)*function1(b);
double absolute = fabs(a-b);
double e = 0;
if (product>0)
{
++a;
++b;
}
else
{
while (absolute >= precision)
{
e = (a + b) / 2;
double fa = function1(a);
double fe = function1(e);
if (fe == 0)
{
return e;
break;
}
if (fa*fe>0)
{
a = e;
}
else if (fa*fe<0)
{
b = e;
}
}
}
return e;
}
Try printing out the values of absolute and precision everytime this loop happens:
while (absolute >= precision)
.
That should help you figure it out.
If the program crashes when you click the button that "calls" on_pushButton_clicked, then it something wrong inside this slot.
Firstly, are all heap memory objects created previously with a new statement (in particular label)?
PS: you can remove the break instruction, function has already exited the while loop due to return in the line before.

Creating new objects in C++ function causes program to crash

I have a program which allows the user to play Dominoes against 3 CPU players, with varying difficulty. Each CPU player can be either Beginner, Intermediate or Expert, and each difficulty has it's own class. If I initiate my 3 CPU players at the beginning of my 'Window' class (below), the program runs fine.
In Window.h
public:
Window(QWidget *parent = 0);
Intermediate *cpu1;
Beginner *cpu2;
Intermediate *cpu3;
In Window.cpp
Window::Window(QWidget *parent):QDialog(parent) {
cpu1 = new Intermediate;
cpu2 = new Beginner;
cpu3 = new Intermediate;
}
However I want the user to be able to select the CPU difficulties at the beginning of the game, so I now have a function within 'Window' that creates the objects. As soon as I call this function the game freezes and I get an error message pop up saying telling me the program has ended unexpectedly.
void Window:: startGame(){
cpu1 = new Intermediate;
cpu2 = new Beginner;
cpu3 = new Intermediate;
}
If anyone would be able to explain to me what is going on and what I can do to get around this that would be great.
Intermediate.cpp (Beginner.cpp is almost identical)
#include "intermediate.h"
Intermediate::Intermediate()
{
tilePlaced = false;
skipGo = false;
}
void Intermediate::findDoubles(int a[7][2]){
for(int i = 0; i < 7; i++){ // Creates new doubles list after each go.
doublesList[i] = 0;
}
for(int i = 0; i < 7; i++){ // Creates a list of doubles
if ((a[i][0] == a[i][1]) && (a[i][0] != 7)){
doublesList[a[i][0]] = 1;
}
}
}
bool Intermediate::addDomino(){} // Function that finds best domino to replace and returns bool
if(tilePlaced == false){
pass++;
text += "\nPassed turn";
return false;
}
else{
pass = 0;
text += QString("\nPlaced [%1 : %2]").arg(a).arg(b);
return true;
}
}
One way to start would be to narrow down which class is causing the fault. Does it work if they are all Beginner, or if they are all Intermediate? If so then the other one is causing the problem.

Segmentation fault occurs only under release configuration

For some odd reason, my application likes to break on me when I switch to release and run it outside of my debugger. Here's what works for me, and here's what doesn't
(Qt Creator is the IDE)
Debugging with debug configuration - ok
Running with debug configuration - ok
Debugging with release configuration - ok
Running with release configuration - application crash
My UI is one project, and the core for some stuff as a separate dependency. On Windows (compiling with MSVCC), I hit a menu button, which eventually calls down to a function. In that function, the app breaks on adding a new element to a vector. e.g:
str *x = new str();
str *y = new str();
/* ...set some of x & y's members... */
vector.push_back(x); // works fine
vector.push_back(y); // causes crash
If I comment out the line vector.push_back(y);, the app continues no problem until the app leaves the event scope (i.e. the end of OnMenuButtonClick). On OS X, it's similar to the issue of adding an element to a vector, except I have:
std::vector<foo *> SomeFunction()
{
std::vector<foo *> returningVector;
/* do stuff */
std::vector<foo *> goo = GetFooObjects();
for (int i = 0; i < goo.size(); i++)
{
returningVector.push_back(goo[i]); // breaks here
}
}
So what are some causes of this strange behavior without a debugger attached and not under debug configuration? I've checked to make sure all of my variables are initialized, so I'm stumped. If you want to view the code above, the first part can be located here, and the second part here. Please forgive anything you see as "bad", and if you have suggestions that you just can't contain, then please do message me on GitHub.
Edit:
I looked more into it, and found out exactly what's causing the problem, but don't know how to fix it. This is the function where my app crashes (on OS X):
vector<Drive *> Drive::GetFATXDrives( bool HardDisks )
{
vector<Drive *> Return;
if (HardDisks)
{
vector<DISK_DRIVE_INFORMATION> Disks = GetPhysicalDisks();
for (int i = 0; i < (int)Disks.size(); i++)
{
DISK_DRIVE_INFORMATION ddi = Disks.at(i);
// First, try reading the disk way
Streams::xDeviceStream* DS = NULL;
try
{
char path[0x200] = {0};
wcstombs(path, ddi.Path, wcslen(ddi.Path));
DS = new Streams::xDeviceStream(ddi.Path);
}
catch (xException& e)
{
continue;
}
if (DS == NULL || DS->Length() == 0 || DS->Length() < HddOffsets::Data)
{
// Disk is not of valid length
continue;
}
DS->SetPosition(HddOffsets::Data);
// Read the FATX partition magic
int Magic = DS->ReadInt32();
// Close the stream
DS->Close();
// Compare the magic we read to the *actual* FATX magic
if (Magic == FatxMagic)
{
Drive *d = new Drive(Disks.at(i).Path, Disks.at(i).FriendlyName, false);
Return.push_back(d);
}
}
}
vector<Drive *> LogicalDisks = GetLogicalPartitions();
for (int i = 0; i < (int)LogicalDisks.size(); i++)
{
Return.push_back(LogicalDisks.at(i));
}
return Return;
}
If I change if (HardDisks) to if (HardDisks = false), the app works just fine. So, I looked into that scope and discovered that after vector<DISK_DRIVE_INFORMATION> Disks = GetPhysicalDisks();, the heap gets corrupt or something like that. I noticed this because in the debugger, after that function is called, my HardDisks bool changes to "false", which wasn't what it was before.
Here is GetPhysicalDisks:
vector<Drive::DISK_DRIVE_INFORMATION> Drive::GetPhysicalDisks( void )
{
// RIGHT AFTER this vector is initialized, everything goes to hell
vector<Drive::DISK_DRIVE_INFORMATION> ReturnVector;
DIR *dir;
dirent *ent;
dir = opendir("/dev/");
if (dir != NULL)
{
// Read the shit
while ((ent = readdir(dir)) != NULL)
{
// Check the directory name, and if it starts with "disk" then keep it!
QRegExp exp("disk*");
exp.setPatternSyntax(QRegExp::Wildcard);
exp.setCaseSensitivity(Qt::CaseInsensitive);
if (exp.exactMatch(ent->d_name))
{
DISK_DRIVE_INFORMATION curdir;
memset(curdir.FriendlyName, 0, sizeof(curdir.FriendlyName));
memset(curdir.Path, 0, sizeof(curdir.Path));
char diskPath[0x50] = {0};
sprintf(diskPath, "/dev/r%s", ent->d_name);
mbstowcs(curdir.Path, diskPath, strlen(diskPath));
int device;
if ((device = open(diskPath, O_RDONLY)) > 0)
{
#ifdef __linux
hd_driveid hd;
if (!ioctl(device, HDIO_GET_IDENTITY, &hd))
{
swprintf(curdir.FriendlyName, strlen(hd) * 2, L"%hs", hd.model);
}
#elif defined __APPLE__
mbstowcs(curdir.FriendlyName, ent->d_name, strlen(ent->d_name));
#endif
ReturnVector.push_back(curdir);
}
}
}
}
return ReturnVector;
}
While this isn't a real answer as to what happened, I did find a way to fix the problem. Looking at my edit above, I edited my Drive::GetFATXDrives function like so:
vector<Drive *> Drive::GetFATXDrives( bool HardDisks )
{
// Initialize Disks vector up here
vector<DISK_DRIVE_INFORMATION> Disks;
// Call the function to get the hard disks
if (HardDisks)
Drive::GetPhysicalDisks(Disks);
vector<Drive *> ReturnVector;
if (HardDisks)
{
Streams::xDeviceStream* DS = NULL;
for (int i = 0; i < (int)Disks.size(); i++)
{
/* ... */
}
if (DS)
{
DS->Close();
delete DS;
}
}
vector<Drive *> LogicalDisks = GetLogicalPartitions();
for (int i = 0; i < LogicalDisks.size(); i++)
{
ReturnVector.push_back(LogicalDisks[i]);
}
return ReturnVector;
}
And my Drive::GetPhysicalDisks function now takes a vector<DISK_DRIVE_INFORMATION> reference instead of returning one. Seemed to make my program work just fine after that.