c++ program stops without errors warnings when printing matrix - c++

I can't seem to find any solution for this.
I have a type 'route' that contains a matrix.if I do:
cout << route << endl;
it works it prints the memory
but if I try
cout << route[1][1] << endl;
program just ends without any error or anything.
debug says:
"(Suspended : Signal : SIGSEGV:Segmentation fault)"
here is the code:
//structure is a type I created
Structure ***route = list->searchRoute(startPoint, destination, time);
//should return a matrix
cout << "Avaible routes: \n" << endl;
for(int i = 0; i < 5;i++)
cout << route[1][1]->startPoint << endl;

Segmentation fault usually implies that you are accessing memory you are not supposed to access. What is probably happening is that our "matrix" is probably too small to have a block in the second row/ second column, so an error is thrown when you try to access that location(because you do not own it). Make sure you are allocating route correctly and at the right size.

Related

Is this a double free in C++

I thought the following code snippets would cause double free, and the program would core dump. But the truth is that there is no error when I run the code?
Similar problem shows that it caused double free!
My Question is why does there have no error show that there is a double free? And why does there have no core dump?
#include <iostream>
using namespace std;
int main()
{
int *p = new int(5);
cout << "The value that p points to: " << (*p) << endl;
cout << "The address that p points to: " << &(*p) << endl;
delete p;
cout << "The value that p points to: " << (*p) << endl;
cout << "The address that p points to: " << &(*p) << endl;
delete p;
cout << "The value that p points to: " << (*p) << endl;
cout << "The address that p points to: " << &(*p) << endl;
delete p;
}
The program's output when I ran this program is shown as followed:
After modifying the code snippet like the following, the core dump occured:
#include <iostream>
using namespace std;
int main()
{
int *p = new int(5);
for (;;)
{
cout << "The value that p points to: " << (*p) << endl;
cout << "The address that p points to: " << &(*p) << endl;
delete p;
}
return 0;
}
And the program output is :
So there is another question that why this program will core dump every time?
Yes, it is a double free (well, triple, really) which puts it into undefined behaviour territory.
But that's the insidious thing about undefined behaviour, it's not required to crash or complain, it's not required to do anything at all(a). It may even work.
I can envisage an implementation that stores the free state of a block in the control information for it so that freeing it twice would have no effect. However, that would be inefficient, and also wouldn't cover the case where it had been reallocated for another purpose (it would prevent double frees, but not a piece of code freeing the block when some other piece still thinks it still has it).
So, given it's not required to work, you would be well advised to steer clear of it since it may also download maniacal_laughter.ogg and play it while erasing your primary drive.
As an aside, modern C++ has smart pointers that are able to manage their own lifetime, and you would be doing yourself a big favour if you started using those instead of raw pointers.And, although the removal of raw pointer from C++ was a joke, there are some that think it's not such a bad idea :-)
(a) The C++20 standard has this to say when describing undefined behaviour in [defns.undefined] (my emphasis):
Behavior for which this document imposes **NO** requirements.
why does there have no error show that there is a double free? And why does there have no core dump?
delete p;
cout << "The value that p points to: " << (*p) << endl;
The moment you referenced to a deleted pointer is when the program entered an undefined behaviour, and then there is no guarantee that there would be an error or a crash.
It's not entirely the same, but the analogy between memory and a hotel room is applicable, which explains well what an undefined behaviour means. Highly recommended reading:
Can a local variable's memory be accessed outside its scope?

storing an object name during construction of another object

I wanted to create objects from the class “takeSnapshots” that would learn, upon their instantiation, the name of another object from the class “lock” that they could query later as the state of the “lock” object changes. I can think of multiple ways of letting the object from class “takeSnapshots” know which object it is to query (like including the name of the “lock” object as part of the call to its member functions). But, I thought it better to take care of the relation in the beginning and not worry later if I am calling the correct object combinations.
The included code shows stripped down versions of the two classes and example instantiations created in main.
I have included the outputs on each line following their respective couts.
What I expected was that the constructor of “takeSnapshots” would store away the address of the “lock” object. Then I could use it later when taking a snapshot. You can see that what gets stored away (at least when I use it to get numWheels) is a few addresses off from the address that the “lock” object thinks it has for numWheels.
I am mostly interested in knowing why this code does not work the way I expect, i.e, if this is not a good architectural idea, that is one thing. But with the behavior I’m seeing here, I’m clearly not ready to use pointers in anything complicated and I don’t want to give up on the basic architecture just because of erroneous implementation. Any help would be greatly appreciated.
// simpleTest.cpp : Demonstrates problem I'm having understanding
// pointer to an object.
#include "stdafx.h"
#include<iostream>
using namespace std;
class lock {
public: //Just while I run a test.
int numWheels;
lock(int numW) {
numWheels = numW;
cout << " \n In \"lock\" constuctor, address and value of numWheels
" << &numWheels << " " << numWheels << endl;
} //Values from console: 0034F874 and 4
};
class takeSnapshots {
lock* localLock;
public:
takeSnapshots(lock myLock) {
localLock = &myLock;
cout << " \n In \"takeSnapshots\" constuctor, address and value of
numWheels " << &localLock->numWheels << " "
<< localLock->numWheels << endl;
//Values from console: 0034F794 and 4 "Same value, but not the same
//address as expected from "lock."
}
void takeASnapSnapshot() {
cout << " \n When taking a snapshot, address and value of numWheels
" << &localLock->numWheels << " " << localLock->numWheels <<
endl;
//Values from console: 0034F794 and 2303449 "No longer even the
// same value as expected from "lock."
}
};
int main()
{
lock yourLock(4);
takeSnapshots myShots1(yourLock);
cout << " \n In main (from \"yourLock\"), address and value of
numWheels " << &yourLock.numWheels << " " << yourLock.numWheels <<
endl;
//Values from console: 0034F874 and 4 "Still the same values as set
//in the constructor of "lock."
//Take a picture
myShots1.takeASnapSnapshot();
return 0;
}

Access Violation Reading Location using open file stream

I know that this question has been asked lots of times. But, in my case, the error is not always present so I think it might be different. I am using C++, Visual Studio 2013, Windows 7 x64.
Here's the relevant code:
void writeDATAToFile(const char *fname, string title, const VecDoub& spec_x, const VecDoub& spec_y, const VecDoub& freq)
{
ofstream of;
of.open(fname, ios_base::out);
if (!of.is_open())
{
return;
}
of << "somename" << endl;
of << "WAVES/S" << "\t" << title << endl;
of << "BEGIN" << endl;
for (int i=0; i<spec_x.size(); i++)
{
of << spec_x[i] << "\t\t\t" << spec_y[i] << "\t\t\t" << freq[i]<<endl;
}
of << "END" << endl;
of.close();
}
This function is supposed to write the spectrum data (calculated earlier in the program) and write it to a file. Some spectrum data won't cause a problem, some will. The error is in the for loop.
Here is the error window:
You're passing 3 vectors to your function:
const VecDoub& spec_x, const VecDoub& spec_y, const VecDoub& freq
but you never check that they have the same size.
In your loop (not the "second" loop as you said in your question, there's just one loop in the code you posted), you're iterating over spec_x and you use the same index i to index into the other two vectors.
What if one or both of your other two vectors have a smaller size than spec_x? Then you're indexing out of bounds which would cause the error you're seeing.
The error message clearly says it is trying to read something it shouldn't be.
You code loops thus:
for (int i=0; i<spec_x.size(); i++)
{
of << spec_x[i] << "\t\t\t" << spec_y[i] << "\t\t\t" << freq[i]<<endl;
}
This assumes spec_x, spec_y and freq are the same size.
You could check this before looping and throw an error if this
precondition doesn't hold.
You could loop up to the smallest size of all three.
You could leave this function as is and put checks where you populate the data originally.
Note - the debugger is trying to help you. If you hit "break" it will five you a call stack, and then you should be able to see exactly which variable is causing the problem.

missing cout before segmentation fault

I had a segmentation fault in my code, so I put many cout on the suspicious method to localise where.
bool WybierajacyRobot::ustalPoczatekSortowania(){
cout << "ustal poczatek sortowania: " << poczatekSortowania << endl ;
list< Pojemnik >::iterator tmp;
cout << "LOL"; // <-- this cout doesn't print when segfault
if (!poczatekSortowania){ // <- T1
cout << "first task" ;
tmp = polka.begin();
}
else{ // <-- T2
cout << " second task " ;// <-- this cout doesn't print when segfault
tmp = ostatnioUlozony;
cout << " debug cout " ; // <-- this cout doesn't print when segfault
++tmp; // <-- segfault
} ...
If the method was call and don't have segfault every cout from T1 and before was printed.
In line ++tmp is segfault because ostatnioUlozony is NULL, when method go to T2 every cout without first wasn't printed. Why?
I'm using Netbeans ang gcc, I found the "segfault line" with debug in Netbeans, but before I use then I spend some time on adding cout line and running program.
Thanks a lot,
You need to flush the output stream with either std::flush or std::endl (which will give a newline as well), otherwise you are not guaranteed to see the output:
cout << " second task " << std::flush;
Nonetheless, you have undefined behaviour if you increment a singular iterator (which the null pointer is), so this is only likely to work. As far as C++ is concerned, your program could launch a nuclear missile instead.
Another solution is to use std::cerr instead of std::cout. It is unbuffered, so no flushing is required, and it's slightly more idiomatic to use std::cerr for debugging purposes.

Unique behavior of my program , Unable to identify

There is some problem during the run time of my program and i am unable to get what the problem is.
what happens basically is , my program automatically closes and displays the following in Microsoft visual c++ 2010 express window
What could be the reasons for this ? I have no idea why this is happening.
Let me tell that in my program i have used pointers too often and have used character arrays which i write to the disc
The program is too large to display
This is the function called after which my program stops :
void display_databases()
{
struct info_of_trains
{
int train_no;
char train_name[25];
char boarding_pt[25];
char destination[25];
int first_seats;
int fare_first;
int second_seats;
int fare_second;
char date[20];
};
info_of_trains e;
cout<<"TRno. TRname B.pt D.pt F.seats F.fare S.seats F.second Date\n";
FILE *fp;
fp=fopen("database","r");
if(fp==NULL)
{
cout<<"failure";
}
else
{
while(fread(&e,sizeof(e),1,fp)==1)
{
printf(e.train_no,e.train_name,e.boarding_pt,e.destination,e.first_seats,e.fare_first,e.second_seats,e.fare_second,e.date);
cout<<"-------------------------------------------------------------------------------\n";
}
fclose(fp);
}
}
This is where execution stops :!
You seem to have hit a breakpoint, or your program had an access violation (reading an illegal pointer). You also seem to have maximized/detached the debugging panels. You can reattach the panel by dragging the yellow bar at the top to the lower part of the screen.
Did you recieve a warning message before it happened? Otherwise, did you define a breakpoint (clicking in the left margin of the code editor, so a red circle appears there)
EDIT: As pointed out in the comments, the error occurs because you use printf the wrong way. Use cout instead, as you did above:
cout << e.train_no <<" " << e.train_name << " " << e.boarding_pt << " " << e.destination << " " << e.first_seats << " " << e.fare_first << " " << e.second_seats << " " << e.fare_second << " " << e.date << endl;