C++ malloc(): memory corruption [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
I am currently going through a fibonacci practice problem on hackerrank and am having a malloc memory corruption error. This is the link to the problem I am doing:
https://www.hackerrank.com/contests/programming-interview-questions/challenges/fibonacci-returns/
Input is 0-10, each number separated by a new line.
For each input, the value at that point in the sequence is printed. It works for small inputs, but after 6 it gets the malloc error. It doesn't seem that the size of the sequence is an issue either, just how many are done in succession.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
vector<int> bigFib(1);
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int x;
while(cin >> x){
if(bigFib.size()-1 >= x){
cout << bigFib[x] << endl;
}
else{
vector<int> fib(x);
fib[0] = 0;
fib[1] = 1;
for(int j = 2; j <= x; j++){
fib[j] = fib[j-1] + fib[j-2];
}
bigFib = fib;
cout << fib[x] << endl;
}
}
return 0;
}
I am pretty new to C++ and can't find the problem. Thanks for your time.

When you create std::vector of size N, you can access elements with index [0, N-1] - which is N elements. You create vector of size x and in your loop:
for(int j = 2; j <= x; j++){
fib[j] = fib[j-1] + fib[j-2];
}
and in this statement
cout << fib[x] << endl;
you try to access element with index equal to x, which is UB. If you do need to access index x create vector with at least x+1 size

In vector<int> fib(x); you declare a vector<int> that has x elements. Those elements are fib[0] through to fib[x - 1]. However, in for(int j = 2; j <= x; j++){ fib[j] = ... you assign to an element out of bounds.
Imagine if x is 1, then you'd expect your fib vector to contain only one element: fib[0]... yet your loop is assigning to fib[1]. Problem? Yup.
I reckon for(int j = 2; j <= x; j++){ should probably be for(int j = 2; j < x; j++){...
... and cout << fib[x] << endl; should be cout << fib[x - 1] << endl;

Related

Value of array index not increasing [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
Here if the condition occurs the value of i store in the array prime. But the index of the array is not increasing, all the values are storing at [0] index and destroy the previous value.
Tried all the other methods but didn't find anything.
I tried prime[x++] and prime[x+1], but they both didn't work for me. If someone gives me a solution then I'll be very thankful to you.
#include<iostream>
using namespace std;
int main()
{
int num = 20, prime[20], x;
for (int i = 1; i <= num; i++) {
if (i % 2 != 0) {
prime[x] = i;
}
}
for (int k = 1; k <= num; k++) {
cout << prime[x] << "\t";
}
}
You have the variable x un-initialized and you are using it, in the line
prime[x] = i;
assuming that it has been initialized. This invokes undefind behavior in your program and the result could not be predicted. Initialize it with the appropriate number to make the program to have a defined behavior.
Regarding prime numbers, see this SO post: Printing prime numbers from 1 through 100.
defining x as uninitialized is a undefined behaviour.
Initialize x as 0 (int x = 0;)
Try with bellow :
int x = 0;
for(int i=1; i<=num; i++){
if(i%2!=0){
prime[x] = i;
x++;
}
}
Now you have the number of prime array elements :
Now print prime array :
for(int k=0; k<x; k++){
cout << prime[k] << "\t";
}
The output (it seems your code detect odd numbers) :
1 3 5 7 9 11 13 15 17 19
Test the code online

C++ - Printing prime numbers till N [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Question says:
You are given an integer N. You need to print the series of all prime numbers till N.
I want to know what's wrong with my code and suggestions will also be of great help.
#include<iostream>
using namespace std;
int main()
{
int N;
cin >> N;
int u;
for(int i = N; i > 0; i--)
{
u = 0;
for(int j = 2; j < N-1; j++)
{
if(i % j == 0)
{
u = 1;
}
}
if(u == 0)
{
cout << i << " ";
}
}
return 0;
}
First for future reference you should probably post that on code review, unless there is a specific problem then you should create a Minimal, Complete, and Verifiable post.
There is nothing inherently wrong other than you do not check that N>0 which could lead to an infinite loop, j should be going to i not N, and I think this would print 1 as a prime number which it is not. Here are some pointers:
Why are you going from N to 0? That seems a little counter intuitive compared from going from 2 to N (you can skip 1 since it is not prime)
If you are going to use a flag (u) then you should make it a bool which forces it to be either true or false
You do not need to do a flag, instead as soon as you find a divisor print the number and then break the inner loop like
for(j=2; j< N-1; j++){
if(i%j==0){
cout << i << " ";
break;
}
}
You do not need to have j go all the way to i, just the sqrt(i) since anything greater then the sqrt(i) that divides i must must be multiplied by some number smaller then the sqrt(i). So if i is not prime, then there must be a divisor below sqrt(i)

I am unable to assign difference of two elements of 2 dimensional array to element of other array in C++? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
Below is the code, which is breaking my head since two days.
#include <iostream>
using namespace std;
int main()
{
int N;
int A[1][N-1];
int B[1][N-1];
std::cout << "ENTER NO OF ROUND" << '\n';
std::cin >> N;
for (int j=0; j<N; j++)
{
int i =0;
std::cout << "enter the scores" << '\n';
std::cin >> A[i][j]>>A[i+1][j];
if (A[i][j] > A[i+1][j])
{
B[i][j] = A[i][j] - A[i+1][j];
B[i+1][j] = 1;
}
if (A[i][j] < A[i+1][j])
{
B[i][j] = A[i+1][j] - A[i][j];
B[i+1][j] = 2;
}
}
std::cout << A[0][0]<<A[1][0] << '\n';
return 0;
}
Here in line 18 line 19 and line23 line24i should get difference of two elements of array A[1][N-1] Which is then assigned to a element in array B[1][N-1],but am unable get the correct result ,rather am getting a random number.
help me getting through this
You use uninitialized data, so anything can happen.
You declare the N variable:
int N;
And then, in the very next line, without assigning any value, you use it to create two arrays using N as a size:
int A[1][N-1];
int B[1][N-1];
This already is a starting point for disaster. Moreover, declaring an array with size [N - 1] is not technically correct - N is a variable, so cannot be used to declare array in this manner. It's a compiler extension (are you using Visual Studio?). If value of N is known, declare it as:
static constexpr size_t N = value;
If it is read at runtime, create your arrays with new or, much better, use std::vector to make your code robust and less error-prone.
The second thing is, that A array is declared as int A[1][N-1];, but you do the following:
int i = 0;
....
if (A[i][j] > A[i+1][j])
Which results in reading A[1][j], which does not exist - in C++ we start indexing from 0! You also modify those non-existing elements:
std::cin >> A[i][j] >> A[i+1][j];
which most likely will result in writing to memory that belongs to B array.
Small notes:
using namespace std seems redundant, as you write std:: everywhere
what is the point of two-dimensional array [M][N] if M = 1?
Use std::vectors if you need arrays with size determined at run-time. The C Variable-length arrays you use are not supported in C++.
std::cout << "ENTER NO OF ROUND" << '\n';
int N = 0;
std::cin >> N;
std::vector<std::vector<int>> A(2, std::vector<int>(N));
std::vector<std::vector<int>> B(2, std::vector<int>(N));
And note that you need 2 x N array because you read both A[i][j] and A[i+1][j] and your for loop is from [0 to N-1] -- N times.

Sum of the first 5 even numbers from the array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 6 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
So, I need to get the sum of the first 5 even numbers from my array, this is the code that I've got so far, have no clue what to do next. It runs, but the result is incorrect
#include "stdafx.h"
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
int niz[10];
cout << "Unesi 10 brojeva:";
for (int i = 0; i < 10; i++) {
cin >> niz[i];
}
int suma = 0;
int parni[5];
int j = 0;
for (int i = 0; i < 10; i++) {
if (niz[i] % 2 == 0) {
niz[i] == parni[j];
j++;
if (j == 5) {
break;
}
}
}
for (int i = 0; i < 5; i++) {
suma = parni[i] + suma;
}
cout << suma;
system("PAUSE");
return 0;
}
This line:
niz[i] == parni[j];
does nothing. (It tests if niz[i] happens to be equal to the current, uninitialized value of parni[j], and throws away the result of the comparison.)
You want to store niz[i] in parni[j], so do this:
parni[j] = niz[i];
Incidentally, there is a problem if there are fewer than 5 even numbers in the niz array. In that case, you still sum up all five entries of the parni array, using uninitialized values, which is Bad. One way to avoid this is to just sum up the even entries as you find them, without using a secondary array.
IE, do suma += niz[i] at the line in question, and get rid of parni altogether.
Unless you're really required to use arrays here, vectors will work much more nicely.
You can also use a couple of standard algorithms to make your life easier (especially std::copy_if and std::accumulate).
// for the moment I'll ignore the code to read the input from the user:
auto input = read_input();
auto pos = std::remove_if(input.begin(), input.end(),
[](int i) { return i % 2 != 0; });
// assume that `input` always contains at least 5 elements
pos = std::min(pos, input.begin() + 5);
sum = std::accumulate(input.begin(), pos, 0);

detecting duplicate in columns of a 2D array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I would like an algorithm that goes through a 2D array and guarantees that each column has all distinct numbers. If a dupe is found in the array it should be replaced with a random number. The random number must also preserve the uniqueness.
If we put a random number, the whole column, should be unique.
is it possible to get an O(N) solution too ?
The best way I can think of is to make an unordered_map<int,bool> for each column, iterate through the column and if you see a number for the first time set the map to true, if the value is already true it's a dupe replace it with a random number. Then check the random number in the map and do the same thing, if it's also a dupe you will have to replace it with a random number again. This algo will like run in linear time, however because of the random number dupe possibility it could run infinitely.
pseudo code
2d_array // assume M rows by N cols
array_of_hashtables // N length
for each col
for each row
if array_of_hashtables[2d_array[row][col]] == false
set it to true
else
do
set 2d_array[row][col] to random
while array_of_hashtables[2d_array[row][col]] == true
end
end
not a huge fan of writing pseudo code but this is about right
Make a std::set and insert step by step elements of every column while checking the size of the set. If the size changes the inserted value is not a duplicate, if it does just randomize a value and add it again to the set. If size changes, you can continue.
Just for the heck of it, here is an implementation of Alexandru Barbarosie's solution:
#include <iostream>
#include <set>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
int L = 3;
int W = 3;
int R = 3;
int a[L][W];
srand(time(NULL));
for (int i = 0; i < L; i++)
{
for (int j = 0; j < W; j++)
{
a[i][j] = rand() % R + 1;
cout << a[i][j] << " ";
}
cout << endl;
}
cout << endl;
set<int> s;
int n = 0;
for (int j = 0; j < W; j++)
{
for (int i = 0; i < L; i++)
{
s.insert(a[i][j]);
if (s.size() != n)
n = s.size();
else
a[i--][j] = rand() % R + 1;
}
s.clear();
n = 0;
}
for (int i = 0; i < L; i++)
{
for (int j = 0; j < W; j++)
cout << a[i][j] << " ";
cout << endl;
}
}