Heap Corruption Detected? - c++
void allocateTriangle(int ** & twoDArray, int numRows);
void printTriangle(int ** twoDArray, int numRows);
void growToSquare(int ** & twoDArray, int numRows);
void printSquare(int ** & twoDArray, int numRows);
using namespace std;
int main(int argc, char ** argv){
srand((unsigned int)time(NULL));
int ** twoDArray;
int numRows = 10;
allocateTriangle(twoDArray, numRows);
cout << "******* Triangle array *******" << endl;
printTriangle(twoDArray, numRows);
growToSquare(twoDArray, numRows);
cout << "******* Sqaure array *******" << endl;
printSquare(twoDArray, numRows);
return 0;
}
void allocateTriangle(int ** & twoDArray, int numRows) {
twoDArray = new int*[numRows];
for (int x = 0; x < numRows; x++){
twoDArray[x] = new int[x];
for (int y = 0; y <= x; y++){
twoDArray[x][y] = rand() % 100;
}
}
}
void printTriangle(int ** twoDArray, int numRows){
for (int x = 0; x < numRows; x++){
for (int y = 0; y <= x; y++){
cout << setw(5);
cout << twoDArray[x][y];
}
cout << endl;
}
}
void growToSquare(int ** & twoDArray, int numRows) {
for (int x = 0; x < numRows; x++){
int *tempArray = new int[x];
*tempArray = *twoDArray[x];
--> delete [] twoDArray[x];
twoDArray[x] = new int[numRows];
for (int y = 0; y < numRows; y++){
if (y <= x)
twoDArray[x][y] = tempArray[y];
else
twoDArray[x][y] = rand() % 100;
}
}
}
void printSquare(int ** & twoDArray, int numRows){
for (int x = 0; x < numRows; x++){
for (int y = 0; y <= numRows; y++){
cout << setw(5);
if (y <= x)
cout << twoDArray[x][y];
else if (y - 1 == x)
cout << " ";
else
cout << twoDArray[x][y - 1];
}
cout << endl;
}
}
The arrow is pointing to where this program likes to crash. Giving me a Heap Corruption, I've spent the last 6 hours looking at this and other posts, I got nothing.
The main gets to growToSquare() and when I try to 'resize' the 2D array by deletion and allocation again, it stopes at deletion. I've commented out other lines to code to see if something else is triggering, nada.
Any words of advice? (I am using Visual studio 2013)
WhozCraig spotted it, in his comment above.
y <= x should be y < x, in multiple places in this code. – WhozCraig
Imagine that numRows is 1 here, for the sake of simplicity. Follow the code logic in that simple case.
void allocateTriangle(int ** & twoDArray, int numRows) {
twoDArray = new int*[numRows];
for (int x = 0; x < numRows; x++){
twoDArray[x] = new int[x];
for (int y = 0; y <= x; y++){
twoDArray[x][y] = rand() % 100;
}
}
}
Here is the code that would execute, which assigns to a zero-length array.
twoDArray = new int*[1];
twoDArray[0] = new int[0];
twoDArray[0][0] = rand() % 100;
Memory has now been corrupted.
Plausible Solution for Triangle Allocation
Though there a about a half-dozen different ways to calculate the indices, this way is likely the easiest to understand.
void allocateTriangle(int ** & twoDArray, int numRows)
{
twoDArray = new int*[numRows];
for (int x = 0; x < numRows; x++)
{
twoDArray[x] = new int[x+1]; // NOTE: size
for (int y = 0; y <= x; y++)
twoDArray[x][y] = rand() % 100;
}
}
void printTriangle(int ** twoDArray, int numRows)
{
for (int x = 0; x < numRows; cout << endl, ++x)
for (int y = 0; y <= x; y++)
cout << setw(5) << twoDArray[x][y];
}
This allows you to keep your indexing (mostly) while sizing the allocations to appropriate lengths.
Growing a Triangle Into A Square
Similarly, the following will extend your triangle into a square. Note: you can invoke this on something already extended to a square. It will simply re-random-generate the right-half diagonal when doing so (and rather expensively at that).
void growToSquare(int ** & twoDArray, int numRows)
{
for (int x = 0; x < numRows; x++)
{
int *tempArray = new int[numRows];
for (int y=0; y<=x; ++y)
tempArray[y] = twoDArray[x][y];
for (int y=x+1; y<numRows; ++y)
tempArray[y] = rand() % 100;
delete [] twoDArray[x];
twoDArray[x] = tempArray;
}
}
void printSquare(int ** & twoDArray, int numRows)
{
for (int x = 0; x < numRows; cout << endl, ++x)
for (int y = 0; y < numRows; y++)
cout << setw(5) << twoDArray[x][y];
}
Output
Using the above methods, your output will look something like this. Obviously the random nature will result in different values, but the important thing is the bottom-left portion of the square retains the original triangle.
******* Triangle array *******
80
80 1
45 93 28
19 96 90 7
38 70 23 26 98
97 26 98 48 37 97
77 25 43 0 28 84 90
95 78 48 16 23 30 14 64
14 29 83 60 7 83 14 77 94
79 1 43 55 22 14 80 34 40 53
******* Sqaure array *******
80 10 62 17 62 94 62 47 87 3
80 1 56 67 56 91 85 51 25 8
45 93 28 9 42 57 95 56 19 42
19 96 90 7 46 67 42 77 53 73
38 70 23 26 98 53 22 34 69 3
97 26 98 48 37 97 8 18 53 55
77 25 43 0 28 84 90 7 82 43
95 78 48 16 23 30 14 64 94 33
14 29 83 60 7 83 14 77 94 75
79 1 43 55 22 14 80 34 40 53
Related
Trying to solve Knights Tour on nested vector<vector<pair<int,int>> but is is not working
I have written a code for knights tour problem which work for 2D array but not for vector<vector<pair<int,int>> WORKING CODE #include <bits/stdc++.h> #define N 8 using namespace std; bool isPossible(int sol[N][N], int x, int y) { if ( sol[x][y]==-1 && x >= 0 && x < N && y >= 0 && y < N) { return true; } return false; } bool KNT(int sol[N][N], int moveNUM, int x, int y, int movex[8], int movey[8]) { int i,next_x,next_y; if (moveNUM == N * N) { return true; } for ( i = 0; i < 8; i++) { next_x = x + movex[i]; next_y = y + movey[i]; if (isPossible(sol, next_x, next_y)) { sol[next_x][next_y]=moveNUM; if (KNT(sol, moveNUM + 1, next_x, next_y, movex, movey)) { return true; } sol[next_x][next_y] = -1; //Backtracking } } return false; } int main() { int sol[N][N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { sol[i][j]=-1; } } int movex[8] = {2, 1, -1, -2, -2, -1, 1, 2}; int movey[8] = {1, 2, 2, 1, -1, -2, -2, -1}; KNT(sol,1,0,0,movex, movey); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout << sol[i][j] << " "; } cout << endl; } } NON WORKING CODE #include <bits/stdc++.h> #define N 8 using namespace std; bool isPossible(vector<vector<pair<int, int>>> &Brd, int x, int y) { if ((Brd[x][y].first == -1) && x >= 0 && x < N && y >= 0 && y < N) { return true; } return false; } bool KNT(vector<vector<pair<int, int>>> &Brd, int moveNUM, int x, int y, int movex[8], int movey[8]) { int i,next_x,next_y; if (moveNUM == N * N) { return true; } for ( i = 0; i < 8; i++) { next_x = x + movex[i]; next_y = y + movey[i]; if (isPossible(Brd, next_x, next_y)) { Brd[next_x][next_y].first = 1; Brd[next_x][next_y].second = moveNUM; if (KNT(Brd, moveNUM + 1, next_x, next_y, movex, movey)) { return true; } Brd[next_x][next_y].first = -1; Brd[next_x][next_y].second = 0; //Backtracking } } return false; //Check for error } int main() { vector<vector<pair<int, int>>> Brd; for (int i = 0; i < N; i++) { vector<pair<int, int>> temp; for (int j = 0; j < N; j++) { temp.push_back(make_pair(-1, 0)); } Brd.push_back(temp); } int movex[8] = {2, 1, -1, -2, -2, -1, 1, 2}; int movey[8] = {1, 2, 2, 1, -1, -2, -2, -1}; KNT(Brd,1,0,0,movex,movey); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout << Brd[i][j].second << " "; } cout << endl; } } In NON WORKING code when I run the code it doesn't give any output but rather ends abruptly. P.S. Any help will mean a lot I have already wasted around 2 days trying to find the solution for this.
Both programs have undefined behavior because you access the 2D array/vector out of bounds. You first check if sol[x][y] == -1 and then you check if x and y are within bounds: bool isPossible(int sol[N][N], int x, int y) { if (sol[x][y]==-1 && x >= 0 && x < N && y >= 0 && y < N) You need to check the bounds first. Your first solution should do: if (x >= 0 && x < N && y >= 0 && y < N && sol[x][y]==-1) Your second solution should do: if(x >= 0 && x < N && y >= 0 && y < N && Brd[x][y].first == -1) Note: The two programs produce different solutions. You'll have to decide which one is correct (if any). First: -1 59 38 33 30 17 8 63 37 34 31 60 9 62 29 16 58 1 36 39 32 27 18 7 35 48 41 26 61 10 15 28 42 57 2 49 40 23 6 19 47 50 45 54 25 20 11 14 56 43 52 3 22 13 24 5 51 46 55 44 53 4 21 12 Second: 0 59 38 33 30 17 8 63 37 34 31 60 9 62 29 16 58 1 36 39 32 27 18 7 35 48 41 26 61 10 15 28 42 57 2 49 40 23 6 19 47 50 45 54 25 20 11 14 56 43 52 3 22 13 24 5 51 46 55 44 53 4 21 12
Flip matrix across its diagonal [closed]
Closed. This question needs to be more focused. It is not currently accepting answers. Want to improve this question? Update the question so it focuses on one problem only by editing this post. Closed 3 years ago. Improve this question What would be the simplest way to reorder my number values in the second matrix with 90 being in the top left and 10 being in the bottom right? My brain is going blank and I know there has to be any easy way to go about this. Any help is appreciated tremendously! Here's what I'm trying to achieve. #include <iostream> using namespace std; void main() { cout << "Before:" << endl; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { int matrix[9][9] = { { 10,11,12,13,14,15,16,17,18 }, { 19,20,21,22,23,24,25,26,27,}, { 28,29,30,31,32,33,34,35,36 }, { 37,38,39,40,41,42,43,44,45 }, { 46,47,48,49,50,51,52,53,54 }, { 55,56,57,58,59,60,61,62,63 }, { 64,65,66,67,68,69,70,71,72 }, { 73,74,75,76,77,78,79,80,81 }, { 82,83,84,85,86,87,88,89,90 } }; cout << matrix[i][j] << " "; } cout << endl; } cout << "After:" << endl; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { int transMatrix[9][9] = { { 10,11,12,13,14,15,16,17,18 }, { 19,20,21,22,23,24,25,26,27,}, { 28,29,30,31,32,33,34,35,36 }, { 37,38,39,40,41,42,43,44,45 }, { 46,47,48,49,50,51,52,53,54 }, { 55,56,57,58,59,60,61,62,63 }, { 64,65,66,67,68,69,70,71,72 }, { 73,74,75,76,77,78,79,80,81 }, { 82,83,84,85,86,87,88,89,90 } }; cout << transMatrix[j][i] << " "; } cout << endl; } }
You could just loop in reverese. for (int i = 8; i >= 0; i--) { for (int j = 8; j >= 0; j--) { //Print element [j][i] here } } Also move the matrix assignment to outside of the loop as pointed out by Federico
Let's consider the following matrix #define ROW 3 #define COL 4 int main() { int mat [ROW][COL] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }; //... return 0; } 1/ If you want the backwards matrix int backwards_mat[ROW][COL]; for(size_t i = 0; i < ROW; ++i) { for(size_t j = 0; j < COL; ++j) { backwards_mat[i][j] = mat[ROW-1-i][COL-1-j]; } } 2/ If you want the transposed matrix int transposed_mat[COL][ROW]; //swap the dimensions for(size_t i = 0; i < ROW; ++i) { for(size_t j = 0; j < COL; ++j) { transposed_mat[j][i] = mat[i][j]; } } If you prints the two matrices, the backwards will be: 12 11 10 9 8 7 6 5 4 3 2 1 And the transposed will be: 1 5 9 2 6 10 3 7 11 4 8 12 You should be able to easily apply this to your matrix.
Do you mean the following? #include <iostream> #include <utility> int main() { const size_t N = 9; int matrix[N][N] = { { 10,11,12,13,14,15,16,17,18 }, { 19,20,21,22,23,24,25,26,27,}, { 28,29,30,31,32,33,34,35,36 }, { 37,38,39,40,41,42,43,44,45 }, { 46,47,48,49,50,51,52,53,54 }, { 55,56,57,58,59,60,61,62,63 }, { 64,65,66,67,68,69,70,71,72 }, { 73,74,75,76,77,78,79,80,81 }, { 82,83,84,85,86,87,88,89,90 } }; for ( const auto &row : matrix ) { for ( const auto &item : row ) std::cout << item << ' '; std::cout << '\n'; } std::cout << '\n'; for ( size_t i = 0; i < N; i++ ) { for ( size_t j = 0; j < N - i - 1; j++ ) std::swap( matrix[i][j], matrix[N-j-1][N-i-1] ); } for ( const auto &row : matrix ) { for ( const auto &item : row ) std::cout << item << ' '; std::cout << '\n'; } std::cout << '\n'; } The program output is 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 90 81 72 63 54 45 36 27 18 89 80 71 62 53 44 35 26 17 88 79 70 61 52 43 34 25 16 87 78 69 60 51 42 33 24 15 86 77 68 59 50 41 32 23 14 85 76 67 58 49 40 31 22 13 84 75 66 57 48 39 30 21 12 83 74 65 56 47 38 29 20 11 82 73 64 55 46 37 28 19 10
Fill Matrix in a special order C++
I want to fill a 8 x 8 matrix with values in a special order (see example below), but I don´t know how to do that. Each numer stands for the ordering number: For example: #3 in the matrix is the third value of a e.g. a measurment I want to add. The Order should be: 1 2 5 6 17 18 21 22 3 4 7 8 19 20 23 24 9 10 13 14 25 26 29 30 11 12 15 16 27 28 31 32 33 34 37 38 49 50 53 54 35 36 39 40 51 52 55 56 41 42 45 46 57 58 61 62 43 44 47 48 59 60 63 64 Does anybody knows an algorithmus to do that? I have tried this, but that´s not a good way to to it, and it´s not working for the whole matrix int b= 0, ii = 0, a = 0, iii = 0 i are different measurement values and now a for loop if (ii == 1) { b++; } if (ii == 2) { a++, b--; } if (ii == 3) { b ++; } tempMatrix[a][b] = i; cout << "TempMatrix " << tempMatrix[a][b] << " a " << a << " b " << b << endl; if (ii == 3) { ii = -1; a --; b ++; } if (iii == 7) { a = a + 2; b = 0; iii = -1; }
Use recursion: #include <iostream> using namespace std; void f(int a[8][8], int current, int x, int y, int size) { if (size == 1) { a[x][y] = current; return; } else { size /= 2; int add_for_each_square = size * size; f(a, current, x, y, size); f(a, current + add_for_each_square, x, y + size, size); f(a, current + 2 * add_for_each_square, x + size, y, size); f(a, current + 3 * add_for_each_square, x + size, y + size, size); } } int main() { int a[8][8]; f(a, 1, 0, 0, 8); for (int i = 0; i < 8; ++i) { for (int j = 0; j < 8; ++j) { cout << a[i][j] << " "; } cout << endl; } }
If the matrix will always be a fixed size, then you can generate two lookup tables for row and column indexes into the matrix. Then, just pass your index through these tables to get the desired positions in the matrix. const auto MATRIX_SIZE = 8; const std::array<int, MATRIX_SIZE*MATRIX_SIZE> row_lookup = {{...}}; //put pre-computed values here. const std::array<int, MATRIX_SIZE*MATRIX_SIZE> col_lookup = {{...}}; for(size_t i = 0; i < MATRIX_SIZE * MATRIX_SIZE; i++) { auto val = get_coefficient(i); auto row = row_lookup[i]; auto col = col_lookup[i]; mat[col][row] = val; }
Debugging a histogram in C++
I want to build a histogram with ell intervals. The size of each interval is computed as k = ceil(m/ell) where m is the maximum number in the data set. That is, the interval i should be [(i - 1) * k, i * k). If a data set is given by the numbers 16 33 55 57 8 47 1 21 14 73 6 59 29 57 20 95 77 5 62 48 and the number of intervals is ell = 10, the histogram has to be textually represented as 0: 4 10: 2 20: 3 30: 1 40: 2 50: 4 60: 1 70: 2 80: 0 90: 1 I need to write a program, that reads in the following values (from the standard input cin) : the number ell of intervals the size n of the data set n non-negative integers Here is my code so far: #include<iostream> #include<math.h> #include<algorithm> using namespace std; int main() { double ell; int n; // size of the data set double m = 0; int * a; int * x; int * y; cin >> ell; cin >> n; a = new int[n]; // finding max element in array a for (int i = 0; i < n; i++) { cin >> a[i]; if (a[i] > m) { m = a[i]; } } int k = ceil(m/ell); x = new int[(int)(ell)]; y = new int[(int)(ell)]; for (int i = 1; i <= ell; i++) { x[i] = (i - 1) * k; for (int j = 0; j < n; j++) { if (a[j] >= (i - 1) * k && a[j] < i * k && x[i] != (ell - 1) * k) { y[i] += 1; } else if (a[j] >= (ell - 1) * k && x[i] == (ell - 1) * k) { y[i] += 1; } else { y[i] += 0; } } cout << x[i] << ": " << y[i] << endl; } delete [] a; delete [] x; delete [] y; return 0; } If I input this: 10 20 16 33 55 57 8 47 1 21 14 73 6 59 29 57 20 95 77 5 62 48 I get 0: 4 10: 2 20: 3 30: 1 40: 2 50: 4 60: 1 70: 2 80: 0 90: 1 But if I input the same many times, I will get a weird output like 0: 4 10: 268501820 20: 1073741827 30: 112 40: 2 50: 4 60: 1 70: 2 80: 0 90: 6 Why is this happening and how can I fix my problem?
x = new int[(int)(ell)]; y = new int[(int)(ell)]; Creates objects on the heap, but unless the objects (i.e. int) have a constructor, then the memory is left uninitialized. The array x is correctly initialized, but y is left (expected to be 0). So the fix is ... x = new int[(int)(ell)]; y = new int[(int)(ell)]; for( int i = 0; i < ell ; i++ ){ x[i] = 0; // tidier to do it obviously. y[i] = 0; // essential to get y[i] += 1; to be meaningful. }
You never initialise your memory. You create dynamic arrays with both x and y but you are not guaranteed that the memory is zeroed. You get lucky for the most part that but when there are values left in the memory your program uses you get the outliers that you see. Put something like this in and it should fix your issues. for(int m = 0;m < (int)ell; m++) { x[m] = 0; y[m] = 0; }
Compare 2D array with some logic, can't think of it
//2D array with row4 and column4 11 12 18 40 14 15 13 22 11 17 19 23 17 14 20 28 My question is how do i looping the idea like this . When looping for [0][0] = 11. for the same entire rows which is 12 , 18 , 40 and same entire column 14 , 11 , 17 cannot be count.going through, After that my second looping will just looping the table sample like this **11** **12** **18** **40** **14** 15 13 22 **11** 17 19 23 **17** 14 20 28 my looping just can read those number without ** . for second time. will choose the second column, which number is smallest and store into a variable temporaryA , and third looping will choose third column, choose smallest value and store into temporaryB, and fourth looping will choose fourth column and store into temporaryC Finally. My answer will be the first number i choose just now ANswer = 11 + temporaryA + temporaryB +temporaryC void BranchandBound( int **minimumCost , int p , int j ){ /* 11 12 18 40 14 15 13 22 11 17 19 23 17 14 20 28 */ bool *stars = new bool[4]; int totalMin = 0; for( int y = 0 ; y < p ; y++ ){ int min,iMin = -1; for( int x = 0 ; x < j ; x++ ){ if( !stars[y] || (iMin < 0 || min > minimumCost[y][x]) ){ min = minimumCost[y][x]; cout << "minimum : " << min << endl; iMin = min; totalMin += min; } stars[iMin] = 1; } } cout << "Total : " << totalMin << endl; }
You want to exclude columns where the minimum was (marked with stars in your question). Let's just remember them: bool stars[4] = { 0 }; Now find the minimum as usual... for (int y = 0; y < sz; y++) { int min, iMin = -1; for (int x = 0; x < sz; x++) { Here, we have to skip columns where minimum already was: if (!stars[x] && (iMin < 0 || min > numbers[x][y])) { min = numbers[x][y]; iMin = x; } And now remember where the next minimum came from: stars[iMin] = 1; } } Done! Summing all the min is left as an exercise to the reader.