Exception thrown at 0x00007FFD9ABF024E (ucrtbased.dll) in myapp.exe: 0xC0000005: Access violation reading location - dynamic-memory-allocation

I'm trying to create a char matrix using dynamic allocation (char**). It represents a board where the margins are '#' character and in the middle is the ASCII 32 (blank space). When I run the code this massage appear: "Exception thrown at 0x00007FFD9ABF024E (ucrtbased.dll) in myapp.exe: 0xC0000005: Access violation reading location " in some cpp file.
Here's my code:
#include <iostream>
using namespace std;
char** allocateBoard(int n)
{
char** Board = 0;
Board = new char* [n+2];
int i;
for (i = 0; i < n + 2; i++)
{
Board[i] = new char[n * 2 + 2];
}
return Board;
}
void initBoard(char**& Board, int n)
{
int i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j < n * 2; j++)
{
if (i == 0 || i == n - 1) Board[i][j] = '#';
else if (j == 0 || j == n * 2 - 1) Board[i][j] = '#';
else Board[i][j] = 32;
}
}
}
void showBoard(char** Board, int n)
{
int i, j;
for (i = 0; i < n; i++)
{
for (j = 0; j < n * 2; j++)
{
cout << Board[i][j];
}
cout << endl;
}
}
int main()
{
int n = 4;
char** Board = 0;
Board = allocateBoard(n);
initBoard(Board, n);
showBoard(Board, n);
cout << endl;
showBoard(Board, n);
for (int i = 0; i < n * 2 + 4; i++)
{
delete[] Board[i];
}
delete[] Board;
return 0;
}
Does anyone know where is the problem? As a very beginner I can't see where is the mistake. I've allocated more space in the matrix than I'm actually using so I can't figure why this message appears. Is the deallocation the problem?
Thanks!

Related

Why am I getting wrong answer for this SPOJ Question

I still dont know weather I am allowed discuss Competetive Programming Doubts here, please let me know..
Can someone help me on this SPOJ question, I am getting wrong Answer:
https://www.spoj.com/problems/SPIKES/
I have tried all the test cases I could think of and the code always gives correct output.
Before posting it here, I also asked it in spoj forum but Its been two days, no one replies...
#include<bits/stdc++.h>
using namespace std;
// # = 35
// # = 64
// . = 46
// s = 115
// Using Dijkstra to find the path with minimum no. of Spikes
int n,m,j;
const int N = 100;
const int INF = 9;
vector<int> g[N];
int vis[N][N];
pair<int,int> dist[N][N];
vector<pair<int,int>> movements = {
{0,1},{0,-1},{1,0},{-1,0}
};
bool isvalid(int i, int j){
return i>=0 && j>=0 && i<n && j<m;
}
void bfs(int sourcei, int sourcej){
set<pair<int,pair<int,int>>> q;
q.insert({0,{sourcei,sourcej}});
dist[sourcei][sourcej] = {0,INF};
while(q.size()>0){
auto curr_v = *q.begin();
int curr_i = (curr_v.second).first;
int curr_j = (curr_v.second).second;
int spikes = curr_v.first;
q.erase(q.begin());
if(vis[curr_i][curr_j]) continue;
vis[curr_i][curr_j] = 1;
for(auto m : movements){
int child_i = curr_i + m.first;
int child_j = curr_j + m.second;
int spikec = spikes;
if(!isvalid(child_i,child_j)) continue;
if(g[child_i][child_j] == 115) spikec = spikes+1;
if(vis[child_i][child_j]) continue;
if(g[child_i][child_j]==35) continue;
if(dist[child_i][child_j].second > spikec){
dist[child_i][child_j] = {(dist[curr_i][curr_j].first +1),spikec};
q.insert({spikec , {child_i,child_j}});
}
}
}
}
int main(){
cin>>n>>m>>j;
int start_j,start_i;
int end_j,end_i;
for (int i = 0; i < N; ++i){
for (int j = 0; j < N; ++j){
dist[i][j].second = INF;
dist[i][j].first = 0;
}
}
for (int i = 0; i < n; ++i){
for (int j = 0; j < m; ++j){
char x; cin>>x;
g[i].push_back((int)x);
if(x=='#') {
start_i = i;
start_j = j;
}
if(x=='x'){
end_i = i;
end_j = j;
}
}
}
bfs(start_i,start_j);
// for (int i = 0; i < n; ++i){
// for (int j = 0; j < m; ++j){
// cout<<dist[i][j].first<<","<<dist[i][j].second<<" ";
// }cout<<endl;
// }
if(dist[end_i][end_j].second <= (int)j/2) cout<<"SUCCESS"<<endl;
else cout<<"IMPOSSIBLE"<<endl;
return 0;
}

stack smashing in C code about making a histogram

I need to make a c program that will make a histogram of all the letters present in a phrase the user gives. When I run it, I does it but gives a "* stack smashing detected *: terminated". Where would this error be coming from? (for ease right now I set max to 3). In the future i'll have it find the max
Thank you
Andrew
#include <stdio.h>
#include <ctype.h>
#include <string.h>
static void ReadText(int histo[26],int max) {
char phrase[100];
int i;
char Letter;
char toArray;
// read in phrase
printf("Enter Phrase: "); // reads in phrase with spaces between words
scanf("%[^\n]",phrase);
// count the number of certain letters that occur
for(i = 0; i <= strlen(phrase);++i) {
Letter = phrase[i];
if(isalpha(Letter) != 0){
Letter = tolower(Letter);
toArray = Letter - 97;
histo[(int)toArray] = histo[(int)toArray] + 1;
}
}
}
static void DrawHist(int histo[26], int max){
int i;
int j;
int histo2[50];
for(i = 0; i <= 26; i++) {
histo2[i+i] = histo[i];
if(i < 25) {
histo2[i+i+1] = 0;
}
}
// (i = 1; i <= 50; i++) {
// printf("%d",histo2[i]);
//}
//printf("\n");
for(i=max;i>0;--i) {
for(j=0;j<=51;++j) {
if((j < 51) && (histo2[j] >= i)) {
printf("|");
}
else if((j < 51) && (histo2[j] < i)){
printf(" ");
}
else if(j == 51){
printf("\n");
}
}
}
printf("+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-\n");
printf("A B C D E F G H I J K L M N O P Q R S T U V W X Y Z\n");
}
int main() {
int histo[26] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
int max = 3;
//int i;
ReadText(histo,max);
//for(i = 0; i<26;++i) {
// printf("%d",histo[i]);
//}
DrawHist(histo,max);
return 0;
}

Clang memory allocation

Could anyone please help me understand why Clang reallocates the same memory address for different variables while their lifetimes intersect?
I am using a sample program (below) to show the problem.
When I compile the program with clang -O0, variable j in function ok has the same memory address as variable solutions in function nqueens.
Function ok is called inside function nqueens, which means that the lifetime of the variables intersect; the same stack space cannot be used/reused for both functions.
Compiling the program with gcc or clang at -O1, however, they are assigned different memory addresses.
Any help is appreciated!
#include <stdlib.h>
#include <stdio.h>
#include <memory.h>
#include <alloca.h>
/* Checking information */
static int solutions[] = {
1,
0,
0,
2,
10, /* 5 */
4,
40,
92,
352,
724, /* 10 */
2680,
14200,
73712,
365596,
};
#define MAX_SOLUTIONS sizeof(solutions)/sizeof(int)
int total_count;
int sharedVar = 0;
int ok(int n, char *a)
{
int i, j;
char p, q;
printf("jjjjjjjjj: %d, %p\n", n,&j);
for (i = 0; i < n; i++) {
p = a[i];
for (j = i + 1; j < n; j++) {
q = a[j];
if (q == p || q == p - (j - i) || q == p + (j - i))
return 0;
}
}
return 1;
}
void nqueens (int n, int j, char *a, int *solutions)
{
int i,res;
sharedVar = sharedVar * j - n;
if (n == j) {
/* good solution, count it */
*solutions = 1;
return;
}
printf("solutions: %d, %p\n", j, &solutions);
*solutions = 0;
/* try each possible position for queen <j> */
for (i = 0; i < n; i++) {
a[j] = (char) i;
if (ok(j + 1, a)) {
nqueens(n, j + 1, a,&res);
*solutions += res;
}
}
}
int main()
{
int size = 3;
char *a;
// printf("total_count: %p\n", &total_count);
total_count=0;
a = (char *)alloca(size * sizeof(char));
printf("Computing N-Queens algorithm (n=%d) ", size);
sharedVar = -5;
nqueens(size, 0, a, &total_count);
printf("completed!\n");
printf("sharedVar: %d\n", sharedVar);
}

How to thresholding image by ourselves without using fucntion in OpenCV

I'm new in OpenCV, and I want to thresholding the image by myself without using Threshold function in opencv, because the time spend on function threshold is to high for me.
Here is my code:
Mat src = imread("D:\\DataBox\\7.jpg", 0);
for (int i = 0; i < src.cols; i++) {
cout << i << endl;
for (int j = 0; j < src.rows; j++) {
if (src.at<uchar>(i, j) > 70) {
src.at<uchar>(i, j) = 0;
cout << j << endl;
}
else
src.at<uchar>(i, j) = 255;
}
}
but it still says:
"OpenCV Error: Assertion failed (dims <= 2 && data && (unsigned)i0 < (unsigned)size.p[0] && (unsigned)(i1 * DataType<_Tp>::channels) < (unsigned)(size.p[1] * channels()) && ((((sizeof(size_t)<<28)|0x8442211) >> ((DataType<_Tp>::depth) & ((1 << 3) - 1))*4) & 15) == elemSize1()) in cv::Mat::at, file C:\Program Files\opencv\build\include\opencv2/core/mat.inl.hpp, line 894"
I can print j from 0~719(since the size of the image is 720*960), but as long as the parameter i want to become 2 from 1, the error occurs.
You mixed up rows and cols:
Try this:
Mat src = imread("path_to_image", IMREAD_GRAYSCALE);
for (int i = 0; i < src.rows; i++)
{
//cout << i << endl;
for (int j = 0; j < src.cols; j++)
{
if (src.at<uchar>(i, j) > 70) {
src.at<uchar>(i, j) = 0;
//cout << j << endl;
}
else
src.at<uchar>(i, j) = 255;
}
}
This is, however very unlikely to perform better than OpenCV implementation. You can gain a little speed working on raw pointers, with a little trick to work on continuous data when possible:
#include <opencv2\opencv.hpp>
using namespace cv;
int main()
{
Mat src = imread("D:\\SO\\img\\nice.jpg", IMREAD_GRAYSCALE);
int rows = src.rows;
int cols = src.cols;
if (src.isContinuous())
{
cols = rows * cols;
rows = 1;
}
for (int i = 0; i < rows; i++)
{
uchar* pdata = src.ptr<uchar>(i);
int base = i*cols;
for (int j = 0; j < cols; j++)
{
if (pdata[base + j] > 70)
{
pdata[base + j] = 0;
}
else
{
pdata[base + j] = 255;
}
}
}
return 0;
}
Actually, on my PC my version is a little bit faster than OpenCV one:
Time #HenryChen (ms): 2.83266
Time #Miki (ms): 1.09597
Time #OpenCV (ms): 2.10727
You can test on your PC with the following code, since time depends on many factor, e.g. optimizations enabled in OpenCV:
#include <opencv2\opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat1b src(720,960);
randu(src, 0, 256);
Mat1b src1 = src.clone();
Mat1b src2 = src.clone();
Mat1b src3 = src.clone();
double tic1 = double(getTickCount());
// Method #HenryChen (corrected)
for (int i = 0; i < src1.rows; i++)
{
//cout << i << endl;
for (int j = 0; j < src1.cols; j++)
{
if (src1.at<uchar>(i, j) > 70) {
src1.at<uchar>(i, j) = 0;
//cout << j << endl;
}
else
src1.at<uchar>(i, j) = 255;
}
}
double toc1 = (double(getTickCount()) - tic1) * 1000.0 / getTickFrequency();
cout << "Time #HenryChen (ms): \t" << toc1 << endl;
//-------------------------------------
double tic2 = double(getTickCount());
// Method #Miki
int rows = src2.rows;
int cols = src2.cols;
if (src2.isContinuous())
{
cols = rows * cols;
rows = 1;
}
for (int i = 0; i < rows; i++)
{
uchar* pdata = src2.ptr<uchar>(0);
int base = i*cols;
for (int j = 0; j < cols; j++)
{
pdata[base + j] = (pdata[base + j] > 70) ? uchar(0) : uchar(255);
}
}
double toc2 = (double(getTickCount()) - tic2) * 1000.0 / getTickFrequency();
cout << "Time #Miki (ms): \t" << toc2 << endl;
//-------------------------------------
double tic3 = double(getTickCount());
// Method #OpenCV
threshold(src3, src3, 70, 255, THRESH_BINARY_INV);
double toc3 = (double(getTickCount()) - tic3) * 1000.0 / getTickFrequency();
cout << "Time #OpenCV (ms): \t" << toc3 << endl;
getchar();
return 0;
}
Use test.at<uchar>(cv::Point(i, j)) instead. I always get lost when accessing cv::Mat directly - cv::Point clears it up a little bit.
Anyway, I agree with Miki - it is very unlikely to create a function that performs better that a library one.

Invalid Conversion from int* to int c++

I've been following a tutorial to try and wrap my head around Dijkstra's shortest path algorithm. Originally it was in Java, but I tried my best to switch it over to C++, but unfortunately I've run into a problem that I can't seem to fix.
here's my code
The error happens in the line
---Distancearray[0] = Testarray[0];
#include <iostream>
using namespace std;
int main(){
int Testarray[5][5] = {{}};
//stores first row of test array
//updates when visiting nodes
int Distancearray[5] = {};
//stores visited nodes
int visitedN[5] = {};
//stores previous node
int PreviousN[5] = {};
//holds the minimum value
int Min = 999999;
//holds the next node value
int NextNode = 0;
cout << "Enter Numbers:\n" << endl;
for(int i=0; i < 5; i++){
//initialize visited array to 0
visitedN[i] = 0;
//same
PreviousN[i] = 0;
for(int j=0; j < 5; j++){
cin >> Testarray[i][j];
if(Testarray[i][j] == 0){
//sets the largest possible number
Testarray[i][j] = 999999;
}
}
}
Distancearray[0] = Testarray[0];
//Sets source node as checked
visitedN[0] = 1;
//Sets distance from sources to 0, starting point
Distancearray[0] = 0;
for(int i=0; i<5; i++){
Min = 9999999;
for(int j = 0; j<5 ; j++){
if(Min > Distancearray[j] && visitedN[j] != 1){
//sets next node to J
Min = Distancearray[j];
NextNode = j;
}
}
visitedN[NextNode] = 1;
for(int i=0; i<5; i++){
if(visitedN[i] != 1){
if(Min+Testarray[NextNode][i] <= Distancearray[i]){
Distancearray[i] = Min+Testarray[NextNode][i];
PreviousN[i] = NextNode;
}
}
}
}
for(int i=0; i<5; i++){
cout << "Lenght" + Distancearray[i] << endl;
}
for(int i=0; i<5; i++){
int j;
cout <<"Path:" + i << endl;
j=i;
do{
j = PreviousN[j];
cout<<"<---" + j<<endl;
}
while(j!=0);
}
return 0;
}
any thoughts?

Resources