Stack Smashing Error While Working with CStrings - c++

I am working on a small project and I am absolutely stuck. The purpose of the function I'm working on is to rearrange and change a Cstring based on a few preset rules. Where my issue lies is within the second portion of my swapping algorithm I came up with.
for(int i = 0; i < len; i++)
{
if(sentence[i] == SPACE)
{
space++;
spacePlace[counter] = i;
counter++;
}
}
for(int i = 0; i < space; i++)
{
if(i == 0)
{
count2 = 0;
for(int h = 0; h < 20; h++)
{
temp1[h] = NUL;
temp2[h] = NUL;
}
for(int j = 0; j < spacePlace[0]; j++)
temp1[j] = sentence[j];
for(int m = spacePlace[0]; m < spacePlace[1]; m++)
{
temp2[count2] = sentence[m];
count2++;
}
.
.
.
the first for loops executes perfectly and the output is great, but the second for loop always messes up and ends up sending me a stack smashing error. For more reference, sentence is a cstring passed to the function, and temp1 and temp2 are also cstrings. Any help or points in the right direction would be a godsend. Thanks!

Related

Segmentation fault - trying to pass matlab code to c ++

I'm trying to pass a code that is in matlab for c ++ but it is giving segmentation fault (core dumped), can someone help me please?
Code in MATLAB
function strip = strips(strip,n,number_pixel)
se = strel('square', 3);
strip=imdilate(strip, se);
strip = imfill(strip);
[m1,n1] = size(strip);
vet=0;
for j=1:n1
for i=1:m1
if strip(i,j)==0
vet=vet+1;
end
end
aux(j)=vet;
vet=0;
end
limite=uint8(number_pixel/4);
for i=1:n1
if aux(i) < limite
strip(:, i)=1;
end
if aux(i) >= limite
strip(:, i)=0;
end
end
end
Code in C++
Mat strips(Mat strip, int n, int number_pixel){
int vet = 0;
int limite = (number_pixel/4);
int v[strip.cols];
dilate(strip, strip, getStructuringElement(MORPH_ELLIPSE, Size(3,3)));
strip = imfill(strip);
int n1 = strip.cols;
int m1 = strip.rows;
for (int j = 0; j < n1; j++){
for (int i = 0; i < m1; i++){
if(strip.at<uchar>(i, j) == 0){
vet += 1;
}
}
v[j] = vet;
vet = 0;
}
for (int i = 0; i < n1; i++){
int j;
if (v[i] < limite){
strip.at<uchar>(i, j) = 1;
}
if (v[i] >= limite){
strip.at<uchar>(i, j) = 0;
}
}
}
I already implemented the functions as imfill, I think my error is in the loop, but I can't find
It is very hard to tell what the problem is, when not having a fully working example. One obvious problem with your code is, that you use j uninitialized in your second loop:
for (int i = 0; i < n1; i++){
int j;
if (v[i] < limite){
strip.at<uchar>(i, j) = 1; // <- uninitialized j is used
}
//...
}
This is undefined behavior and basically everything could happen. j allocates memory but does not have a specific value. See this answer:
Local variables get their initial values from whatever random data is in the stack space they occupy at that moment.
That is j could be a very large integer and you try to access a value out of bounds. Or using j itself causes the error. As I said, the behavior is undefined.
EDIT I also think the second part of your code should be changed. strip(:,i)=1 sets the ith column of the 2D array to 1. Assuming that strip.at<uchar>(i, j) returns only a reference to a single value, your c++ code should be something like this:
for (int i = 0; i < n1; i++){
if (v[i] < limite){
// go through all rows and set the i-th column to 1.
for (int j = 0; j < m1; ++j)
strip.at<uchar>(j, i) = 1;
}
//...
}

2048 - How do I stop my tiles from merging twice?

I'm trying to make a merging algorithm and it works fine except for one thing: a single tile can merge twice in one move so 4224 becomes 8400 instead of 4440 when I move left.
I've tried adding a break statement at the end of the else if block and adding a flag if a tile has merged but none of these things helped. I sincerely apologise for any mistakes that I might have made but this is my first post on stackoverflow.
#define TILES_X 4
#define TILES_Y 4
//Moving UP with SDL library
for (int i = 0; i < TILES_X; i++) {
for (int j = 1; j < TILES_Y; j++) {
if (gameBoard[i][j] != 0) {
for (int k = 0; k < j; k++) {
if (gameBoard[i][k] == 0) {
gameBoard[i][k] = gameBoard[i][j];
gameBoard[i][j] = 0;
}
else if (gameBoard[i][k] == gameBoard[i][j] && (gameBoard[i][k+1]==0||gameBoard[i][k+1]==gameBoard[i][k])) {
gameBoard[i][k] = 2 * gameBoard[i][j];
gameBoard[i][j] = 0;
}
}
}
}
}

Counting Sort in C++

I am trying to implement the Counting Sort in C++ without creating a function. This is the code that I've written so far, but the program doesn't return me any values. It doesn't give me any errors either. Therefore, what is wrong?
#include <iostream>
using namespace std;
int main()
{
int A[100], B[100], C[100], i, j, k = 0, n;
cin >> n;
for (i = 0; i < n; ++i)
{
cin >> A[i];
}
for (i = 0; i < n; ++i)
{
if (A[i] > k)
{
k = A[i];
}
}
for (i = 0; i < k + 1; ++i)
{
C[i] = 0;
}
for (j = 0; j < n; ++j)
{
C[A[j]]++;
}
for (i = 0; i < k; ++i)
{
C[i] += C[i - 1];
}
for (j = n; j > 0; --j)
{
B[C[A[j]]] = A[j];
C[A[j]] -= 1;
}
for (i = 0; i < n; ++i)
{
cout << B[i] << " ";
}
return 0;
}
It looks like you're on the right track. You take input into A, find the largest value you'll be dealing with and then make sure you zero out that many values in your C array. But that's when things start to go wrong. You then do:
for (i = 0; i < k; ++i)
{
C[i] += C[i - 1];
}
for (j = n; j > 0; --j)
{
B[C[A[j]]] = A[j];
C[A[j]] -= 1;
}
That first loop will always go out of bounds on the first iteration (C[i-1] when i=0 will be undefined behavior), but even if it didn't I'm not sure what you have in mind here. Or in the loop after that for that matter.
Instead, if I were you, I'd create an indx variable to keep track of which index I'm next going to insert a number to (how many numbers I've inserted so far), and then I'd loop over C and for each value in C, I'd loop that many times and insert that many values of that index. My explanation may sound a little wordy, but that'd look like:
int indx = 0;
for(int x = 0; x <= k; x++) {
for(int y = 0; y < C[x]; y++) {
B[indx++] = x;
}
}
If you replace the two loops above with this one, then everything should work as expected.
See a live example here: ideone

How can I not allow an element in an array to not increment if it was already incremented on that run in the loop?

I am trying to get the summary of CFG with given input. I have to list the terminals with the count of how many times it appears in the rule. However, I'm having trouble with it counting multiple terminals on the same rule.
for (int i = 0; i < cfg.size(); i++)
{
for (int j = 0; j < cfg[i].size(); j++)
{
for (int k = 0; k < terminal.size(); k++)
{
if (strcmp(cfg[i][j].c_str(), terminal[k].c_str()) == 0)
{
//TO-DO if counter[k] already incremented do not increment counter[k] again
counter[k]++;
break;
}
}
}
}
For example if the rule is
Z -> a b b b
It will return 3 for b when the correct answer would be 1.
Any help on how I can how I can leave that rule after it has already been counted would be great. Thank you
I'm not sure if I understand what you mean, but maybe changing the loops order would help?
for (int i = 0; i < cfg.size(); ++i)
{
for (int k = 0; k < terminal.size(); ++k)
{
for (int j = 0; j < cfg[i].size(); ++j)
{
if (strcmp(cfg[i][j].c_str(), terminal[k].c_str()) == 0)
{
++counter[k];
break;
}
}
}
}

Get rid of goto statement from embedded C/C++ logic

I want to get rid of this goto statement. Can any one tell me the logic for the same. The code below is not the exact code that I want to modify, but it will support my question. Please don't ask the significance of the code when commenting on this post as it is just an example.
int result[i][j];
for (int i = 0; i<100; i++)
{
for (j = 0; j<100; j++)
{
result[i][j] = j++;
if (j == 80)
goto break1;
}
}
break1:
…;
Put those loops in a function, give it a proper name and return; when it is done. If it is complicated enough to need two loops, it deserves a name.
A finished flag is so hard to read that you should put that construct in its own function anyway, making it obsolete.
Exceptions are only for errors you cannot handle locally. Use them to notify higher level functions that something you cannot fix went wrong, not if something that was supposed to happen happened.
I would see three possible solutions.
Put the code into a function and leave that function with return
Use a "finished" flag like already demonstrated well in the answers by Michel Keijzers, Bas in het Feld and EvilTeach.
(C++ only) surround the code-section with a try-catch-block and throw and exception when you want to leave the code. But keep in mind that exceptions are usually supposed to be used for error-handling. So you should only use this pattern when terminating the loops is the result of an error conditions.
Since you want to break two loops, you have to notify the outer loop. You can do this by having a boolean that checks for that:
bool break_loop = false;
for (int i = 0; i < 100; ++i) {
for (int j = 0; j < 100; ++j) {
if (j == 80) {
break_loop = true;
break;
}
}
if (break_loop) break;
}
Use a boolean to break from the for loop(s).
int result[i][j];
bool cont = 1;
for (int i =0;i<100;i++)
{
for(j = 0;j<100;j++)
{
result[i][j] = j++;
if(j == 80)
{
cont = 0;
break;
}
}
if (cont == 0)
break;
}
break1;
(note: not tested on real compiler).
int result[i][j];
for (int i = 0; i<100; i++)
{
for (j = 0; j<100; j++)
{
result[i][j] = j++;
if (j == 80)
{
i = 100;
break;
}
}
}
I sometimes like changing the control variable(s)
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 100; j++) {
/* work */
if (j == 80) i = j = 100; // 100 makes both loops terminate
}
}
int result[i][j];
for (int i = 0; i<100; i++)
{
int j;
for (j = 0; j<100; j++)
{
result[i][j] = j++;
if (j == 80)break;
}
if(j == 80) break;
}
Know this is an old question but can be modified simply