Access Violation Reading Location - c++

I have a problem with VC++, simply, I hate it haha. My code seems to be running all fine on my Mac but when I try to run it in VC++, I get this error in debug:
Windows has triggered a breakpoint in Assignment1-FINAL.exe.
This may be due to a corruption of the heap, which indicates a bug in
Assignment1-FINAL.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while
Assignment1-FINAL.exe has focus.
I know for a fact I haven't pressed F12 so I am not sure why I am getting this... Then, when I try to run it in Release mode, I get this:
Unhandled exception at 0x00401473 in Assignment1-FINAL.exe:
0xC0000005: Access violation reading location 0x00347015.
This is the code I am using:
int countPointsAboveThreshold(point * points, double threshold_distance) {
int i = 1;
int count = 0;
while (points[i - 1].end != true) {
point pointOne = points[i -1];
point pointTwo = points[i];
double distance = distanceBetweenTwoPoints(pointOne, pointTwo);
if (pointTwo.end == true) {
if (distance > threshold_distance) {
count++;
return count;
} else {
return count;
}
} else if (distance > threshold_distance) {
count++;
}
i++;
}
return count;
}
int totalPoints(point * points) {
int i = 0;
while (points[i].end != true) {
i++;
}
return i + 1;
}
point * findLongPaths(point * points, double threshold_distance) {
int i = 1;
int locationToStore = 0;
int pointsAboveThreshold = countPointsAboveThreshold(points, threshold_distance);
point * pointsByThreshold = new point[pointsAboveThreshold];
pointValues * pointsToCalculate = new pointValues[pointsAboveThreshold];
while (points[i - 1].end != true && i < pointsAboveThreshold) {
point pointOne = points[i - 1];
point pointTwo = points[i];
//Check to see if the distance is greater than the threshold, if it is store in an array of pointValues
double distance = distanceBetweenTwoPoints(pointOne, pointTwo);
if (distance > threshold_distance) {
pointsToCalculate[i - 1].originalLocation = i - 1;
pointsToCalculate[i - 1].distance = distance;
pointsToCalculate[i - 1].final = pointTwo;
pointsToCalculate[i - 1].stored = false;
//If the final point has been calculated, break the loop
if (pointTwo.end == true) {
pointsToCalculate[i].end = true;
break;
} else {
pointsToCalculate[i - 1].end = false;
i++;
continue;
}
}
}
if (points[0].end == true && pointsAboveThreshold == 0) {
point emptyPoint;
emptyPoint.x = 0.0;
emptyPoint.y = 0.0;
emptyPoint.end = true;
pointsByThreshold[0] = emptyPoint;
return pointsByThreshold;
}
//Find the point with the lowest distance
int j = 2;
//EDITED
pointValues pointWithLowest;
pointWithLowest = pointsToCalculate[0];
while (pointsToCalculate[j - 1].end != true) {
for (int k = 1; pointsToCalculate[k - 1].end != true; k++) {
if (pointsToCalculate[k - 1].stored == true) {
k++;
continue;
} else {
if (pointsToCalculate[k - 1].distance > pointWithLowest.distance) {
pointWithLowest = pointsToCalculate[k - 1];
k++;
continue;
} else if (pointsToCalculate[k - 1].distance == pointWithLowest.distance) {
if (pointWithLowest.originalLocation < pointsToCalculate[k - 1].originalLocation) {
pointWithLowest = pointsToCalculate[k - 1];
k++;
continue;
} else {
k++;
continue;
}
} else {
pointWithLowest.stored = true;
pointsByThreshold[locationToStore] = pointWithLowest.final;
locationToStore++;
break;
}
}
}
//DEBUGGER STOPS HERE
j++;
}
delete[] pointsToCalculate;
return pointsByThreshold;
}
And this is the main function:
point *longest_calculated = findLongPaths(p, 1.1);
std::cout << "Should equal " << longest[1].y << ": " << longest_calculated[1].y;
delete longest_calculated;
cin.get();
return 0;

Inital thoughts:
Where's the asserts? Your accessing Points* in countPointsAboveThreshold() as an array, but do no bounds checking at all to make sure you aren't pass the array's end. This would be my first area of checking for memory stomping action. Also, straight pointer calls are very C. Heck, you aren't check bounds in any of your array calls. Dangerous...
Newing arrays of length 0 may or may not be safe. I'd be careful of that.
Heck anytime I see [i - 1] in a statement I get nervous. Very easy to read garbage at i == 0
i,j,k loops with quadrouple nested ifs mixed with continues and a break? No. Rethink that logic. It is way, WAY too complicated.
You are early returning with memory allocated in pointsToCalculate[]. Memory leak there.
Might I suggest breaking your last function into multiple parts to simplify the logic?
Man I hate K&R style brackets. Your choice though - not here to start that holy war :P
Beyond that, I'd go with my first suggestion and make sure that your end bool is set always and that you aren't going out of bounds. As previously suggested, stl::vector and a few references (preferably const) are your friend here.

You posted this as C++ but it seems to be using very little of what C++ actually is all about: objects. This code reads much more like C.
Just some notes:
With C++ you don't need to do typedef struct {...} point, doing struct point {...} does what you are trying to do.
If you use a stl::vector instead of a c-array then your loops will become much simpler and you won't need your function totalPoints(). You can also get rid of the member variable end from point and pointValues
You are creating a lot of variables on the heap rather than on the stack for no good reason. With stl::vector (or other standard containers), local variables, and references you can greatly simplify your memory management and avoid strange crashes such as these.
I'll take a deeper look at your code and see if I can give you some more specific guidance but you really should do some further reading into what C++ provides over C. I'd take a look at cplusplus.com and the C++ FAQ. There are also some excellent book suggestions here.

This part of your code sounds odd to me:
if (distance > threshold_distance) {
pointsToCalculate[i - 1].originalLocation = i - 1;
pointsToCalculate[i - 1].distance = distance;
pointsToCalculate[i - 1].final = pointTwo;
pointsToCalculate[i - 1].stored = false;
...
I think you need to use another index variable (other than i - 1) to populate pointsToCalculate!
I would rewrite this part something like this:
int i = 1;
int index = 0;
// if points[i - 1].end is true how you could access points[i] ?
while (points[i].end != true && i < pointsAboveThreshold) {
point pointOne = points[i - 1];
point pointTwo = points[i];
//Check to see if the distance is greater than the threshold, if it is store in an array of pointValues
double distance = distanceBetweenTwoPoints(pointOne, pointTwo);
if (distance > threshold_distance) {
pointsToCalculate[index].originalLocation = i - 1;
pointsToCalculate[index].distance = distance;
pointsToCalculate[index].final = pointTwo;
pointsToCalculate[index].stored = false;
++ index;
}
++i;
}
pointsToCalculate[index].end = true;
** Also note that you need at least two points in your array or you get access violation again, so you need to check for this and you have the same problem in "countPointsAboveThreshold" function that you need to fix too.
Please check for syntax and typos ;)
But any way I strongly recommend following two last post recommendations too.

Related

Deleting an array works on CodeBlocks but not on Visual

I'm building a class and at some point I call a delete. In codeblocks it works and in Visual Studio 2013 it doesn't.
In my class I have:
private:
bool sign; // 0 if positive, 1 if negative
int NumberSize;
int VectorSize;
int *Number;
Then I have this function:
void XXLint::Edit(const char* s)
{
// Get Size
this->NumberSize = strlen(s);
// Initialise Sign
if (s[0] == '-')
{
this->sign = 1;
s++;
}
else if (s[0] == '+') s++;
else this->sign = 0;
delete[] Number; // Here the debugger gives me the error
//Get Vector Size
this->VectorSize = this->NumberSize / 4;
// Allocate Memory
this->Number = new int[this->VectorSize];
//Store the string into the number vector.
int location = this->VectorSize;
int current = this->NumberSize - 1;
while (location)
{
int aux = 0;
for (int i = 3; i >= 0 && current; i--)
if (current - i >= 0)
aux = aux * 10 + s[current - i] - '0';
current -= 4;
this->Number[location--] = aux;
}
}
I did read the article and it really is interesting :D but i don't belive that's where the error comes from.
Why is this error happening?
Look here:
this->Number = new int[this->VectorSize];
int location = this->VectorSize;
Assume for argument's sake that this->VectorSize == 10. So location now has the value 10. However, later you do this in a loop:
while (location)
{
//...
this->Number[location--] = aux; // out of bounds!
}
You are accessing this->Number[10]. That is a memory overwrite. And no, location doesn't get decremented before it's used, as it is post-decrement, not pre-decrement.
When you compile a program on another compiler and then run the program, if that runtime detects errors, always question your code. It doesn't matter if it "worked" on compiler X, or if it worked on your computer and your friend's computer but not the teacher or customer's computer. Always suspect there is something wrong with your code if there is a failure such as memory corruption.

Dynamic Programming for analyzing a Vector of Vector of Bools

Here's the problem I'm trying to solve.
Given a square of bools, I want to find the size of largest subsquare entirely full of trues (1's). Also, I am allowed O(n^2) memory requirement as well as the run time must be O(n^2). The header to the function will look like the following
unsigned int largestCluster(const vector<vector<bool>> &map);
Some other things to note will be there always be at least one 1 (a 1 x 1 subsquare) and the input will also always be a square.
Now for my attempts at the problem:
Given this is based on the concept of dynamic programming, which to my limited understanding, helps store information that is previously found for later use. So if my understanding is correcting, Prim's algorithm would be an example of a dynamic algorithm because it remembers what vertices we've visited, the smallest distance to a vertice, and the parent that enables that smallest distance.
I tried analyzing the map and keeping track of the number of true neighbors, a true location location has. I was thinking if a spot had 4 true neighbors than that is a potential subsquare. However, this didn't help with subsquares of size 4 or less..
I tried to include a lot of detail in this question for help as I'm trying to game plan a way to tackle this problem because I don't believe it's going to require writing a lengthy function. Thanks for any help
Here's my nomination. Dynamic programming, O(n^2) complexity. I realize that I probably just did somebody's homework, but it looked like an intriguing little problem.
int largestCluster(const std::vector<std::vector<bool> > a)
{
const int n = a.size();
std::vector<std::vector<short> > s;
s.resize(n);
for (int i = 0; i < n; ++i)
{
s[i].resize(n);
}
s[0][0] = a[0][0] ? 1 : 0;
int maxSize = s[0][0];
for (int k = 1; k < n; ++k)
{
s[k][0] = a[k][0] ? 1 : 0;
for (int j = 1; j < k; ++j)
{
if (a[k][j])
{
int m = s[k - 1][j - 1];
if (s[k][j - 1] < m)
{
m = s[k][j - 1];
}
if (s[k - 1][j] < m)
{
m = s[k - 1][j];
}
s[k][j] = ++m;
if (m > maxSize)
{
maxSize = m;
}
}
else
{
s[k][j] = 0;
}
}
s[0][k] = a[0][k] ? 1 : 0;
for (int i = 1; i <= k; ++i)
{
if (a[i][k])
{
int m = s[i - 1][k - 1];
if (s[i - 1][k] < m)
{
m = s[i - 1][k];
}
if (s[i][k - 1] < m)
{
m = s[i][k - 1];
}
s[i][k] = ++m;
if (m > maxSize)
{
maxSize = m;
}
}
else
{
s[i][k] = 0;
}
}
}
return maxSize;
}
If you want a dynamic programming approach one strategy I could think of would be to consider a box (base case 1 entry) as a potential upper left corner of a larger box and start by the bottom right corner of your large square, you then need to evaluate only the "boxes" (using information previously stored to only consider the largest cluster so far) that are to the right, bottom, and diagonally right-bottom of that we are now evaluating.
By saving information about each edge we would be respecting the O(n^2) (though not o(n^2)) however for the run-time you need to work on the details of the approach to get to O(n^2)
This is just a rough draft idea as I don't have much time, and I would appreciate any more hints/comments about this myself.

BFS maze help c++

I am attempting to make a maze-solver using a Breadth-first search, and mark the shortest path using a character '*'
The maze is actually just a bunch of text. The maze consists of an n x n grid, consisting of "#" symbols that are walls, and periods "." representing the walkable area/paths. An 'S' denotes start, 'F' is finish. Right now, this function does not seem to be finding the solution (it thinks it has the solution even when one is impossible). I am checking the four neighbors, and if they are 'unfound' (-1) they are added to the queue to be processed.
The maze works on several mazes, but not on this one:
...###.#....
##.#...####.
...#.#.#....
#.####.####.
#F..#..#.##.
###.#....#S.
#.#.####.##.
....#.#...#.
.####.#.#.#.
........#...
What could be missing in my logic?
int mazeSolver(char *maze, int rows, int cols)
{
int start = 0;
int finish = 0;
for (int i=0;i<rows*cols;i++) {
if (maze[i] == 'S') { start=i; }
if (maze[i] == 'F') { finish=i; }
}
if (finish==0 || start==0) { return -1; }
char* bfsq;
bfsq = new char[rows*cols]; //initialize queue array
int head = 0;
int tail = 0;
bool solved = false;
char* prd;
prd = new char[rows*cols]; //initialize predecessor array
for (int i=0;i<rows*cols;i++) {
prd[i] = -1;
}
prd[start] = -2; //set the start location
bfsq[tail] = start;
tail++;
int delta[] = {-cols,-1,cols,+1}; // North, West, South, East neighbors
while(tail>head) {
int front = bfsq[head];
head++;
for (int i=0; i<4; i++) {
int neighbor = front+delta[i];
if (neighbor/cols < 0 || neighbor/cols >= rows || neighbor%cols < 0 || neighbor%cols >= cols) {
continue;
}
if (prd[neighbor] == -1 && maze[neighbor]!='#') {
prd[neighbor] = front;
bfsq[tail] = neighbor;
tail++;
if (maze[neighbor] == 'F') { solved = true; }
}
}
}
if (solved == true) {
int previous = finish;
while (previous != start) {
maze[previous] = '*';
previous = prd[previous];
}
maze[finish] = 'F';
return 1;
}
else { return 0; }
delete [] prd;
delete [] bfsq;
}
Iterating through neighbours can be significantly simplified(I know this is somewhat similar to what kobra suggests but it can be improved further). I use a moves array defining the x and y delta of the given move like so:
int moves[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};
Please note that not only tis lists all the possible moves from a given cell but it also lists them in clockwise direction which is useful for some problems.
Now to traverse the array I use a std::queue<pair<int,int> > This way the current position is defined by the pair of coordinates corresponding to it. Here is how I cycle through the neighbours of a gien cell c:
pair<int,int> c;
for (int l = 0;l < 4/*size of moves*/;++l){
int ti = c.first + moves[l][0];
int tj = c.second + moves[l][1];
if (ti < 0 || ti >= n || tj < 0 || tj >= m) {
// This move goes out of the field
continue;
}
// Do something.
}
I know this code is not really related to your code, but as I am teaching this kind of problems trust me a lot of students were really thankful when I showed them this approach.
Now back to your question - you need to start from the end position and use prd array to find its parent, then find its parent's parent and so on until you reach a cell with negative parent. What you do instead considers all the visited cells and some of them are not on the shortest path from S to F.
You can break once you set solved = true this will optimize the algorithm a bit.
I personally think you always find a solution because you have no checks for falling off the field. (the if (ti < 0 || ti >= n || tj < 0 || tj >= m) bit in my code).
Hope this helps you and gives you some tips how to improve your coding.
A few comments:
You can use queue container in c++, its much more easier in use
In this task you can write something like that:
int delta[] = {-1, cols, 1 -cols};
And then you simple can iterate through all four sides, you shouldn't copy-paste the same code.
You will have problems with boundaries of your array. Because you are not checking it.
When you have founded finish you should break from cycle
And in last cycle you have an error. It will print * in all cells in which you have been (not only in the optimal way). It should look:
while (finish != start)
{
maze[finish] = '*';
finish = prd[finish];
}
maze[start] = '*';
And of course this cycle should in the last if, because you don't know at that moment have you reach end or not
PS And its better to clear memory which you have allocate in function

C++ memory: deleting an unused array of bool can change the result from right to wrong

I am trying to solve Project Euler Problem 88, and I did it without too much effort; however, I find that some seemingly irrelevant code in my program is affecting the result. Here's my complete code (it's not short, but I cannot locate the error. I believe it would be obvious to more experienced eyes, so please read my description first):
#include <iostream>
#include <set>
using namespace std;
bool m[24001][12001];
bool p[24001]; // <------------ deleting this line will cause error in result!
long long answer[12001];
int main() {
long long i;
long long j;
long long l;
set<long long> all;
long long s = 0;
for (i = 0; i <= 24000; i++) {
for (j = 0; j <= 12000; j++) {
m[i][j] = false;
}
}
m[1][1] = true;
for (i = 2; i <= 24000; i++) {
m[i][1] = true;
for (j = 2; (j <= i) && (i * j <=24000); j++) {
for (l = 1; l <= i; l++) {
if (m[i][l]) {
m[i * j][l + 1 + (i * j) - i - j] = true;
}
}
}
}
for (i = 0; i <= 24000; i++) {
for (j = 0; j <= 12000; j++) {
if (m[i][j] && (answer[j] == 0)) {
answer[j] = i;
}
}
}
for (i = 2; i <= 12000; i++) {
cout << answer[i] << endl;
all.insert(answer[i]);
}
cout << all.size() << endl;
for (set<long long>::iterator it = all.begin(); it != all.end(); it++) {
//cout << *it << endl;
s += *it;
}
cout << s << endl;
}
With the "useless" bool array, all the answers are right, between 0 and 24000; but without it, some answers in the middle got corrupted and become very large numbers.
I am completely confused now; why would that unused array affect the middle of the answer array?
Thanks and sorry for the long code! I will be grateful if someone could edit the code into a better example, I simply son't know what is with the code.
You do a silly thing in here:
m[i * j][l + 1 + (i * j) - i - j] = true;
Say, i=160, j=150, l=1... You will try to access m[24000][23692]... And you corrupt the stack, so behavior is undefined.
Next time try to use some profiler and/or debugger.
Add:
#include <cassert>
at the begining and
assert( (i * j) * 12001 + (l + 1 + (i * j) - i - j) <= 12001*24001 );
before the following line:
m[i * j][l + 1 + (i * j) - i - j] = true;
The assertion will fail, which means you write outside the bounds of the array m.
As requested, adding this to an answer.
You are definitely writing beyond the bounds of the array m somewhere, when the unused array p exists, m overwrites in to its contents which doesn't affect the answer array but once p is removed the overwriting happens in to answer array showing up the problems.
Overwriting beyond the bounds of the array is an Undefined Behavior and it causes your program to be ill-formed. With Undefined Behavior all safe bets are off and any behavior is possible. While your program may work sometimes or crash sometimes or give incorrect results.Practically, Anything is possible and the behavior may or even may not be explainable.
In one of your nested loops you use l as the index for the second dimension. This variable can run from 0 to i and i, in turn, can run from 0 to 24000. Since your second dimension of the array can only be index from 0 to 12000 this causes a classic out of range error. This also nicely explains why adding an extra array avoid the problem: the out of range accesses go to the "unused" array rather than overwriting the result.

C++: delete strange behaviour

I have started doing some stuff with dynamic allocation in C++ but I had some problems. Here's the code:
nrMare(char cifS[], char* startPos = new char())
{
n = 0;
int i;
cif = startPos;
printf("%p %i\n", cif, (cif - (char*)NULL) % 8);
for(i = strlen(cifS) - 1; i >= 0; i--)
{
cif--;
n++;
cif = new(cif) char(cifS[i] - '0');
}
}
~nrMare()
{
int i;
for(i = 0; i < n; i++)
{
delete(cif);
cif++;
}
n = 0;
cif = 0;
}
nrMare is a class (it comes from bigNumber in Romanian :D) which is supposed to be able to contain the digits of a big number.
The problem is that the destructor (~nrMare) gives a weird error, when I make a variable nrMare something() on my computer, but it works for 116 digits long ones.
Do you have any suggestion or explainations?
EDIT: cif is a (char*) type
EDIT #2: n is the length of the number. I use the char pointer this way because I want to be able to add (like n++; cif--; cif = new(cif) char(number_to_add); -> this would add number_to_add in the left side of cif) and draw elements from both sides.
EDIT #3: this is gonna be a long one... Sorry for being such a bad explainer and thanks for your patience.here are some operators:
void operator-=(nrMare nr2)
{
int i;
for(i = 1; i <= n && i <= nr2.n; i++)
cif[n - i] -= nr2[nr2.n - i];
for(i = n - 1; i >= 0; i--)
{
if(cif[i] < 0)
{
cif[i] += 10;
cif[i - 1]--;
}
}
while(cif[0] == 0)
{
cif++;
n--;
//delete(cif - 1);
}
}
int operator/=(int nr)
{
int i;
for(i = 0; i < n - 1; i++)
{
cif[i + 1] += (cif[i] % nr) * 10;
cif[i] = cif[i] / nr;
}
i = cif[n - 1] % nr;
cif[n - 1] /= nr;
while(cif[0] == 0)
{
cif++;
n--;
//delete(cif - 1);
}
return i; // the return value is this big number % nr
}
void operator*=(int cifTimes)
{
int i;
for(i = 0; i < n; i++)
{
cif[i] *= cifTimes;
}
for(i = n - 1; i >= 0; i--)
{
if(cif[i] > 9)
{
if(i != 0)
{
cif[i - 1]++;
cif[i] %= 10;
}
else
{
n++;
cif[0] %= 10;
cif--;
cif = new(cif) char(cif[0] = 1);
}
}
}
}
EDIT #4: n = length of the number = number of digits = number of bytes. Weird error means it just crashes. I don't know how to find more about it. MinGW compiler asks Visual Studio (Visual C++) to debug it because it has some problems. This is for a problem, and somewhere (in the evaluator) it says "Killed by signal 6(SIGABRT)", if this helps.
EDIT #...: #Branko Dimitrijevic: I don't wanna be lazy... I want my own... I had this problem in more attempts to make something running. If I take out the destructor, it works just fine, just I guess then it would be a memory leak that way... I really want to find out why would this occur... and only for specific sizes and, i.e. it doesn't crash on the first "delete", but on the 11'th in my case, that's why it's weird .
The delete can only work correctly on an address that is at the beginning of a dynamically-allocated block.
The cif will fail one or both of these conditions, leading to undefined behavior when the destructor calls delete, for following reasons:
You assign startPos to cif and then modify it in a very strange way before calling the placement new. So even if startPos is a properly allocated block of dynamic memory, the cif no longer points to the starting address of it.
If the caller passes an address of a stack-based variable to startPos, then you no longer deal with dynamic memory at all.
Not to mention that you call new and delete in a loop - what's up with that? There is also a fair chance for bombarding the memory unless you craft your input parameters in a very specific way. This whole block of code looks suspicious, what exactly are you trying to do?