Another program crash on vector.push_back() - c++

I am writing a program that reads in data from text files, sorts the data in various ways and then uses the sorted data for other calculations. Let me say that in int main(){ } there is one large for-loop that contains many other for-loops and that the segment of code that I am posting is just one of those many for-loops inside the main one.
for(t=(compare.t - 1000)*2 - 12 ;t< ( (compare.t - 1000)*2 + 12 /);t++){
rank.push_back(vector <int>() );p++;
for(ii=111;ii<2489;ii++){
if(M_screened[a][ii].size()>0){
if( fabs(M_screened[a][ii][0].t-(t*0.5 + 1000.0)) <0.257 ){
cout<<"ii = "<<ii<<" t = "<<t<<" sizeof(rank) = "<<rank.size()<<" p = "<<p;
cout<<" rank["<<p<<"].size() = "<<rank[p].size()<<endl;
cout<<" "<<endl;
cout<<"address = "<<&rank[p][rank[p].size()-1];
rank[p].push_back(ii);
cout<<" "<<endl;
}
}
}
foutT<<t*0.5 + 1000<<" "<<frequency[a][t]<<endl;} //end t-loop
All of the cout statements were just part of my own error checking process. Also, the large for-loop that contains the above code segment is able to run 2 iterations prior to crashing on the third (every single time).
Basically what I've narrowed it down to is crashing on the push_back() function. Parameter values at the time of crash:
t=177, p = 10, ii = 873, sizeof(rank) = 11, rank[10].size() = 1
Here is the error message I get from Microsoft Visual Studio :
Unhandled exception at 0x0000000077993290 (ntdll.dll) in Muon_fitting7_7_2014_statistics.exe: 0xC0000005: Access violation reading location 0x0000038085FFA1E8.
If I can provide any additional information please let me know.

I am assuming you've initialized P to zero or some such thing when declared and that is actually your problem.
for(t=(compare.t - 1000)*2 - 12 ;t< ( (compare.t - 1000)*2 + 12 /);t++)
{
rank.push_back(vector <int>() );p++;
for(ii=111;ii<2489;ii++)
{
if(M_screened[a][ii].size()>0){
if( fabs(M_screened[a][ii][0].t-(t*0.5 + 1000.0)) <0.257 ){
rank[p].push_back(ii);
}
}
}
}
At first, rank has no elements, then you push back and increment p. Now rank as 1 element but you need to use rank[p-1] to access it as p is already 1. That or initialize p to -1 to start so when you increment it, its at zero. Vector [] access is zero based.
So, try this :
int p = -1;
for(t = ((compare.t - 1000)*2 - 12);t < ((compare.t - 1000)*2 + 12);++t)
{
rank.push_back(vector <int>() );
++p;
for(ii=111;ii<2489;++ii)
{
if (M_screened[a][ii].size() > 0)
{
if (fabs(M_screened[a][ii][0].t-(t*0.5 + 1000.0)) < 0.257)
{
rank[p].push_back(ii);
}
}
}
}

Related

which digital filter is this analysing code

I am going through a program with zero comments.
This is a signal filter, and I would like to know which type this is
So far I have this:
arrays (lengths = order):
X: contains previous filter input values
Y: contains previous filter output values
A: contains coeficients
B: contains coeficients
Filter steps:
formula roughly:
OUT = SUM(i=0 to order)( X[i]*B[i] - Y[i]*A[i])
shifting the window: all X's and Y's move one position, removing the oldest values and the new input and output value are added.
I tried googling which kind of filter this is, but I am a bit stuck, especially the feedback of the previous outputs is something I did not see before (I only used very very simple filters before).
source:
`float_type floatFilter::addPoint(float_type P)
{
//P is sample value`
if (_pfilterCoefs == NULL) return P;
//
if (_reset)
{
for (uint16_t i=0;i<_pfilterCoefs->order;i++)
{
*(_Ys+i)= _pfilterCoefs->lowpass ? P : 0;
*(_Xs+i)= _pfilterCoefs->lowpass ? P : 0;
}
_reset=false;
}
//calculate output
float_type Y = ((*_pfilterCoefs->Bs)) * P;
for (uint16_t i=0; i<_pfilterCoefs->order; i++)
{
Y+=(*(_Xs+i)) * (*(_pfilterCoefs->Bs + (_pfilterCoefs->order-i))) -
(*(_Ys+i)) * (*(_pfilterCoefs->As + (_pfilterCoefs->order-1-i)));
}
//move filter one step (
for (uint16_t i = 0; i<(_pfilterCoefs->order-1);i++)
{
*(_Ys+i)=*(_Ys+i+1);
*(_Xs+i)=*(_Xs+i+1);
}
*(_Xs + _pfilterCoefs->order - 1) = P; //the most recent input is added in the end
*(_Ys + _pfilterCoefs->order - 1) = Y; //the most recent output is added in the end
return *(_Ys + _pfilterCoefs->order-1); //this is the most recent output.

how can I assign value into 2-D array by using their address?

I'm going to rewrite a program that is using pointer & dynamic array
but for 2-D array part, here are some question
This is the original code:
for (int index = 0; index < 12; index++)
{
sorted[index][0] = sum[index];
sorted[index][1] = index+1;
}
And I rewrite it like this :
for (int index = 0; index < 12; index++)
{
*(*sorted+index) = *(sum+index);
*((*sorted+index)+1) = index + 1;
}
I have tried and the problem is occur in first part of the assign
*(*sorted+index) and *((*sorted+index)+1)
what is the problem going on? There are no error code, the descrition is just:
Exception thrown at 0x00F47379 in ass2 Q3.exe: 0xC0000005: Access
violation writing location 0xCE13E05C. Unhandled exception at
0x00F47379 in ass2 Q3.exe: 0xC0000005: Access violation writing
location 0xCE13E05C.
You have a problem in these 2 lines:
*(*sorted+index) = *(sum+index);
*((*sorted+index)+1) = index + 1;
You need to move the sorted pointer by index offset, and to do so you should write (sorted + index) now you can get the value stored in this address by *(sorted + index) then get the first element by *(*(sorted + index)). The same thing must be applied to the second line too, so those 2 lines should be:
*(*(sorted+index)) = *(sum+index);
*(*(sorted+index)+1) = index + 1;
I suggest that you read more about pointer arithmetic.

Another C++ strange segmentation fault by object creation

I've recently encountered a problem in c++ object creation. The problem is somewhat like it in question C++ strange segmentation fault by object creation, however the codes here are part of an open source project and may not have easy errors.
The object creation is called in a method and the method is called in two continuous steps.
The class is defined in strtokenizer.h as follows:
class strtokenizer {
protected:
vector<string> tokens;
int idx;
public:
strtokenizer(string str, string seperators = " ");
void parse(string str, string seperators);
int count_tokens();
string next_token();
void start_scan();
string token(int i);
};
And in strtokenizer.cpp, it is like this:
using namespace std;
strtokenizer::strtokenizer(string str, string seperators) {
parse(str, seperators);
}
void strtokenizer::parse(string str, string seperators) {
int n = str.length();
int start, stop;
if (flag) {
printf("%d\n", n);
}
start = str.find_first_not_of(seperators);
while (start >= 0 && start < n) {
stop = str.find_first_of(seperators, start);
if (stop < 0 || stop > n) {
stop = n;
}
tokens.push_back(str.substr(start, stop - start));
start = str.find_first_not_of(seperators, stop + 1);
}
start_scan();
}
int strtokenizer::count_tokens() {
return tokens.size();
}
void strtokenizer::start_scan() {
idx = 0;
return;
}
string strtokenizer::next_token() {
if (idx >= 0 && idx < tokens.size()) {
return tokens[idx++];
} else {
return "";
}
}
string strtokenizer::token(int i) {
if (i >= 0 && i < tokens.size()) {
return tokens[i];
} else {
return "";
}
}
The method that create the strtokenizer objects is as follows:
int dataset::read_wordmap(string wordmapfile, mapword2id * pword2id) {
pword2id->clear();
FILE * fin = fopen(wordmapfile.c_str(), "r");
if (!fin) {
printf("Cannot open file %s to read!\n", wordmapfile.c_str());
return 1;
}
char buff[BUFF_SIZE_SHORT];
string line;
fgets(buff, BUFF_SIZE_SHORT - 1, fin);
int nwords = atoi(buff);
for (int i = 0; i < nwords; i++) {
fgets(buff, BUFF_SIZE_SHORT - 1, fin);
line = buff;
strtokenizer strtok(line, " \t\r\n");
if (strtok->count_tokens() != 2) {
continue;
}
pword2id->insert(pair<string, int>(strtok->token(0), atoi(strtok->token(1).c_str())));
}
fclose(fin);
return 0;
}
When the read_wordmap() method is run for the first time (first read_wordmap() call), the 'strtok' object is created about 87k times and in the second time (second read_wordmap() call), the oject is expected to be run for more than 88k times. However, it will raise a error (sometime 'segmentation fault' and sometimes 'memory corruption (fast)') at about 86k times in the second method call, at the line:
strtokenizer strtok(line, " \t\r\n");
And when the code block of object creation is revised like those below, there will be no errors.
strtokenizer *strtok = new strtokenizer(line, " \t\r\n");
printf("line: %s", line.c_str());
if (strtok->count_tokens() != 2) {
continue;
}
pword2id->insert(pair<string, int>(strtok->token(0), atoi(strtok->token(1).c_str())));
It look like you have a memory corruption in your code. You should consider using a tool like valgrind (http://valgrind.org/) to check that the code does not write out of bounds.
Your revised code use heap memory instead of stack memory, which may hide the problem (even if it still exists).
By reading your code, there is several missing tests to ensure safe handling in case the provided wordmapfile has some unexpected data.
For example you do not check the result of fgets, so if the number of words at the begining of the file is bigger than the real number of words, you will have issues.
I carefully debugged my code under the suggestion of #Paul R and other friends and found it is because I haven't free memory in stack.
The codes proposed above are tiny parts of my project, and in the project a gibbs sampling algorithm is supposed to run for one thousand times(iterations).
In each iteration, old matrixes are supposed to be freed and new ones are to be "newed out". However, I forgot to free all the matrix and lists, and that's why my program corrupts.
The reason why I posted codes above is that the program will crash every time when it ran into the line:
strtokenizer strtok(line, " \t\r\n");
The object "strtok" will be run for 1000 * lines in files(with 10000+ lines). So it made me think maybe there are too many objects created and take up all of the stack memory. Even though I found there are no need to manually free them.
When debugged the program in visual studio, the monitor of memory occupancy showed a dramatic growth in each iteration and "bad_alloc" error took place every now and then. These made me realize that I forget to free some large dynamic matrix.
Thanks for you all!
And I apologise for the wrongly described question that takes up your time!

Why is this code showing some junk type of value when it shows the correct value on my machine?

I am trying to write a code for implementing Djisktra's Algorithm... And having some problem with it
The link to the code is Ideone...
When the same code is run over my PC the output comes out to be
0 4 12 19 21 11 9 8 14
And the output one ideone is
0 4 12 19 21 11 9 8 16777230
See the difference in the last element 14...I am pretty clueless about it... Is there some error in my code ? Or it is happening due to some other reason over online compilers or am I doing something stupid?
Potential Error here
int find(int start)
{
int low=INT_MAX,idx=-1,i;
for(i=0;i<V;i++)
if( !(Left[i]) && low>=Distances[i])
{
idx=i;
low=Distances[i];
}
return idx;
}
while(start != -1)
{
for(i = 0; i < V; i++)
if(graph[start][i] && Distances[start] + graph[start][i] < Distances[i])
Distances[i] = graph[start][i] + Distances[start];
start = find(start);
Left[start] = true;
}
I have tried finding the reason.. The distance at V-1 is 14 at some point(I tried printing it) but it is not updated Later(I tried printing it whenever the distance of V-1 was updated) But it seems it was not updated later on!!
I am a beginner please do tell me where am I going wrong
NOTE: (Graph is a 2D adjacency matrix) Distances is an array of int type and Left is of bool type )
You have undefined behavior in the while loop in the code on ideone which doesn't match the code you've posted here. This is why others admonish you for not providing a minimal example. When find returns -1, Left[start] = true accesses before the start of the array. Since it is undefined behavior, it could do anything, including work correctly on your PC and fail on ideone. To fix, since you have a Left[start] = true before the while loop, remove it, and move it to the top of the while:
while(start != -1)
{
Left[start] = true;
for(i = 0; i < V; i++)
if(graph[start][i] && Distances[start] + graph[start][i] < Distances[i])
Distances[i] = graph[start][i] + Distances[start];
start = find(start);
}
Corrected code on ideone (also removed some unused variables).

Deleting 2d array in C++

Can some one tell me what is wrong in the for loop? When I run it, it interrupts. I tried to debug to see what is wrong, I noticed that in the for loop it just stops:
#define MAX_POPULATION 64
float **tr_pop;//Tournament candidates
float **matingPool;//Mating pool
tr_pop=new float *[m];
matingPool=new float *[m];
for(l=0;l<m+1;l++)//allocating
{
tr_pop[l]=new float[MAX_POPULATION];
matingPool[l]=new float[MAX_POPULATION];
}
for ( int r = 0; r < row; ++r )//deleting
{
delete [] matingPool[r];//Stops here (not ending program just frozen)
delete [] tr_pop[r];
}
delete [] tr_pop;
delete [] matingPool;
=======OK. PROBLEM SOLVED=======
Here is the reason:
I just changed the MAX_POPULATION into the MAX_POPULATION+1 and it worked.
for(l=0;l<m+1;l++)
{
tr_pop[l]=new float[MAX_POPULATION+1];
matingPool[l]=new float[MAX_POPULATION+1];
}
Because in another function I think I was doing violation:
void crossover()
{
int p1,p2,i,j;float tempBit;
p1=m/3;
p2=(2*m)/3;
for(j=0;j<MAX_POPULATION;j++)
{
for(i=p1;i<p2;i++)
{
tempBit=matingPool[i][j];
matingPool[i][j]=matingPool[i][j+1];//THE VIOLATION POINT (I THINK)
matingPool[i][j+1]=tempBit;
}
j++;
}
As you can see, when j = MAX_POPULATION at the end of the loop, i was trying to reach MAX_POPULATION + 1. So I changed the allocations for columns, and the problem solved :)
You're running into undefined behavior:
for(l=0;l<m+1;l++)//allocating
{
tr_pop[l]=new float[MAX_POPULATION];
}
should be
for(l=0;l<m;l++)//allocating
{
tr_pop[l]=new float[MAX_POPULATION];
}
You're allocating m elements for each of the arrays and try to access m+1.
You are allocating m float* but in for loop you are iterating from 0..m while allocating memory, it should from 0..m-1. For that you need to chnage the for loop to : for(l=0;l<m;l++).