Segmentation fault when remove duplicate value in pointer array - c++

When debugging, I found that segmentation fault caused after copy from temp array (b) to original array (a), I don't know how to solve this, can you guys help me on that?
#include <iostream>
using namespace std;
int main() {
int n;
cout << "n = ";
cin >> n;
int *a = new int[n];
for (int i = 0; i < n; i++)
cin >> a[i];
cout << "\nNumber to remove: ";
int k;
cin >> k;
for (int i = 0; i < n; i++)
{
while (a[i] == k && i < n - 1)
{
int *b = new int[n]{0};
for (int j = 0; j < i; j++)
b[j] = a[j];
for (int j = i + 1; j < n; j++)
b[j - 1] = a[j];
a = NULL;
delete a;
n--;
int *a = new int[n];
for (int j = 0; j < n; j++)
a[j] = b[j];
}
}
cout << "Result: ";
for (int i = 0; i < n; i++)
cout << a[i] << " ";
}

The problem with this implementation lies here:
a = NULL;
delete a;
When you use the delete keyword you are telling the compiler to free the memory allocated by a new keyword, in this case you have a which is a pointer to the memory allocated by int *a = new int[n];. a at this point would probably be a 32bit address for example 0xbfebd5c0, i said probably because it depends on the architecture of the machine, however... after that you are setting a to NULL resulting in a being 0x0, at the next while condition check a is NULL and accessing 0x0 + i is not possible due to safety reasons imposed by the OS (no one gave you access to this location). The solution to your specific problem would be removing a = NULL; and delete a; as both these operations interfere with the while condition check.
I would suggest to take another approach at solving this problem since you really don't need to do this many dynamic allocations.

Related

C++ Memory leak error when resizing C++ dynamic array

The code below converts lets say array 3,9,3 to sorted array of integers 3,3,3,3,3 by converting 9 into sum of maximum possible parts.
The link to code/algorithm used in this code is answered at
https://stackoverflow.com/a/75331557/21145472
I am struck in this C++ code. When I ran it yesterday it was fine but today it gives memory leak error when function resizeArray() is run third time.
Please help fix this memory leak
#include<cmath>
#include <algorithm>
#include <iterator>
using namespace std;
void resizeArray(int *orig, int size, int newSize) {
int *resized = new int[newSize];
for (int i = 0; i < size; i ++)
resized[i] = orig[i];
delete [] orig;
orig = resized;
}
int main(){
int n = 3;
int *arr = new int[n];
int arrLength = n;
arr[0] = 3;
arr[1] = 9;
arr[2] = 3;
int *arrSorted = new int[0];
int sortedArrayLength = 0;
int temp;
unsigned long long int limit = 10e4;
long long parts = 0;
int extra = 0;
int mainArrayIndex = 0;
for(int i = 0; i<n/2; i++){
temp = arr[i];
arr[i] = arr[n-i-1];
arr[n-i-1] = temp;
}
for(int i = 0; i < n; i++){
parts = floor((arr[i] - 1) / (limit)) + 1;
limit = arr[i] / parts;
extra = arr[i] % parts;
for(int index = 0; index < extra; index++){
resizeArray(arrSorted, sortedArrayLength, sortedArrayLength + 1);
arrSorted[mainArrayIndex] = limit+1;
mainArrayIndex+=1;
sortedArrayLength+=1;
}
for(int index = 0; index < parts - extra; index++){
resizeArray(arrSorted, sortedArrayLength, sortedArrayLength + 1);
arrSorted[mainArrayIndex] = limit;
mainArrayIndex+=1;
sortedArrayLength+=1;
}
}
cout << "Array sorted steps taken" << " " << sortedArrayLength - arrLength;
cout << endl;
for(int i = 0; i < sortedArrayLength; i++){
if(i == 0)
cout << "[";
cout << arrSorted[i];
if(i < sortedArrayLength - 1)
cout << ", ";
if(i == sortedArrayLength - 1)
cout << "]";
}
delete []arr;
delete []arrSorted;
}
Your helper function's orig = resized; doesn't reassign your main function's arrSorted as you intend. Use a reference:
void resizeArray(int *&orig, ...) {
(That and the lack of including iostream are the only correctness issues I see, and this fix got rid of the error.)

Code Exiting on above 500,000 number of input

I was performing sorting algorithm to calculate their runtime to execute, in which I was giving millions of number of input to sort, but my code is exiting on above 500,000 input and not showing any output. Is there anyway I can solve it.
int size;
cout<<"Enter size of the array: "<<endl;
cin>>size;
int a[size];
for(int i=0;i<size;i++)
{
a[i]=rand()%size;
}
int temp = 0;
double cl=clock();
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (a[j] < a[i])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
double final=clock()-cl;
cout<<final/(double)CLOCKS_PER_SEC;
}
You code crashes on 500'000 input because of stack overflow, you're allocating array on stack of too big size:
int a[size];
Stack size is usually few megabytes at most.
Also it is probably an extensions not of all compilers to have dynamically allocated array on stack, usually size should be a compile time constant.
To overcome stack crash either you have to use std::vector which can provide any size as big as there is free memory, for that do:
std::vector<int> a(size);
(also #include <vector>). Or you may use dynamically allocated array through new operator:
int * a = new int[size];
For this case don't forget to do delete[] a; at the end of program (see docs here).
Don't forget that input 500'000 takes very much of time using your bubble sort. For example 10 times less, 50'000, takes around 10 seconds on my machine.
Full working code using std::vector plus code formatting:
Try it online!
#include <iostream>
#include <vector>
using namespace std;
int main() {
int size;
cout << "Enter size of the array: " << endl;
cin >> size;
std::vector<int> a(size);
for (int i = 0; i < size; i++) {
a[i] = rand() % size;
}
int temp = 0;
double cl = clock();
for (int i = 0; i < size; i++) {
for (int j = i + 1; j < size; j++) {
if (a[j] < a[i]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
double final = clock() - cl;
cout << final / (double)CLOCKS_PER_SEC;
}

Why does this selection sort code shows different output when running again as compared to first time

Firstly when I have code this program it was running perfectly but running it again, it is not showing expected output can someone tell what's wrong with it
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
int arr[n];
int loc,min;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
for (int i = 0; i < n - 1;i++){
min = arr[i];
for (int j = i + 1; j < n; j++)
{
if(min>arr[j]){
min = arr[j];
loc = j;
}
swap(arr[loc],arr[i]);
}
}
for (int i = 0; i < n; i++){
cout << arr[i] << " ";
}
cout << endl;
}
Forgoing the fact that variable-length arrays are not part of standard C++ (and thus code tutorials that use them should be burned), the code has two main problems.
On an already sorted sequence, the inner-most if body will never be entered, and therefore loc will never receive a determinate value.
The swap is in the wrong place..
Explanation
Within your code...
using namespace std;
int main(){
int n;
cin >> n;
int arr[n];
int loc,min; // loc is INDETERMINATE HERE
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
for (int i = 0; i < n - 1;i++){
min = arr[i];
for (int j = i + 1; j < n; j++)
{
if(min>arr[j]){
min = arr[j];
loc = j; // loc ONLY EVER SET HERE
}
swap(arr[loc],arr[i]); // loc IS USED HERE EVEN IF NEVER SET
}
}
for (int i = 0; i < n; i++){
cout << arr[i] << " ";
}
cout << endl;
}
The purpose of the inner loop is to find the location (loc) of the most extreme value (smallest, largest, whatever you're using for your order criteria) within the remaining sequence. No swapping should be taking place in the inner loop, and the initial extreme value location (again, loc) should be the current index of the outer loop (in this case i)
Therefore...
We don't need min. It is pointless.
We must initialize loc to be i before entering the inner loop.
We swap after the inner loop, and then only if loc is no longer i.
The result looks like this.
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
for (int i = 0; i < n - 1; i++)
{
int loc = i;
for (int j = i + 1; j < n; j++)
{
if (arr[loc] > arr[j])
loc = j; // update location to new most-extreme value
}
// only need to swap if the location is no longer same as i
if (loc != i)
swap(arr[loc], arr[i]);
}
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
The line swap(arr[loc],arr[i]); should be outside the inner for loop, so move it one line down.
Also, you will want to initialize loc to i at the start of the outer for loop.
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
int arr[n];
int loc,min;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
for (int i = 0; i < n - 1;i++){
min = arr[i];
loc=i;
for (int j = i + 1; j < n; j++)
{
if(min>arr[j]){
min = arr[j];
loc = j;
}
swap(arr[i],arr[loc]);
}
}
for (int i = 0; i < n; i++){
cout << arr[i] << " ";
}
cout << endl;
}

Finalize the magic square generator

This code that runs only for odd N. The problem is that there are no ideas how to add support for even values N
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
setlocale(0, "");
int n;
cout << "Enter the size of the magic square - ";
cin >> n;
int **matrix = new int *[n];
for (int i = 0; i < n; ++i)
{
matrix[i] = new int[n];
}
int nsqr = n * n;
int i = 0, j = n / 2;
for (int k = 1; k <= nsqr; ++k)
{
matrix[i][j] = k;
i--;
j++;
if (k % n == 0)
{
i += 2;
--j;
}
else
{
if (j == n)
{
j -= n;
}
else if (i < 0)
{
i += n;
}
}
}
cout << "\n\nMagic square size - " << n << "\n\n";
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << matrix[i][j] << "\t";
}
cout << endl;
}
for (i = 0; i < n; i++)
delete[] matrix[i];
delete[] matrix;
system("pause >> null");
return 0;
}
I would be grateful for tips on troubleshooting.
If i'm not mistaken, the problem is in this line:
int i = 0, j = n / 2;
But i don't know how to change the code to support even values
I would assume that you meant normal magic square (where the number are restricted to 1,2..n^2)
First of all, it's impposible to construct such magic square for n=2.
2nd, you would need an whole new algorithm for it, which is much more complicated. The problem (constructing magic square for any even number) is solved in this paper and while there isn't any psaudo code there, the implementation from the explenation is quite straightforward (long one though).
the problem is here:
i = 0;
int j = n / 2;
for (int k = 1; k <= nsqr; ++k)
{
matrix[i][j] = k;
i--;
}
look how you decrement i inside the loop and making it as an index of the array so:
matrix[-3][j] = k; // will be in your code
you are messing deliberately with the indexes of the array
I found answer on my question in this artcile
I made full revision my algorithm based on this article. Later posted listing the resulting program

Position 2D array bug as parameter causes memory dumps

This is my program in C++, which accepts an 2D array a[m][n]. If an element a[i][j] is zero, then set all the ith row and jth column elements to zero.
This is code sample:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
class SetZero{
public:
static void setZero(int **, int , int);
};
void SetZero::setZero(int ** a, int m, int n){
int i, j, k;
int ** b = new int *[m]; //flags to identify whether set to zero or not.
for(i = 0; i < m; i++){
b[i] = new int[n];
for(j = 0; j < n; j++)
b[i][j] = 1;
}
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
if(a[i][j] == 0 && b[i][j]){//DUMP here. If I change it to (a+i)[j], then works.
for (k = 0; k < n; k++){
a[i][k] = 0;//but there is NO dump here. Weird!
b[i][k] = 0;
}
for(k = 0; k < m; k++){
a[k][j] = 0;
b[k][j] = 0;
}
j = n;//break. next row loop.
}
for(int i = 0; i < m; i++)
delete[] b[i];
delete[] b;
}
int main(){
int a[4][5];
srand(time(NULL));
for(int i = 0; i < 4; i++){//create an 2D array
for(int j = 0; j < 5; j++){
a[i][j] = rand() % 100;
cout << a[i][j] << " ";
}
cout << endl;
}
SetZero::setZero((int **)a, 4, 5);//type cast.
cout << endl;
for(int i = 0; i < 4; i++){//print result
for(int j = 0; j < 5; j++)
cout << a[i][j] << " ";
cout << endl;
}
return 0;
}
Environment: WIN8 Visual Studio 2012.
Edit:
The program can compile but cannot execute normally. It will stop when it reaches if(a[i][j] == 0 && b[i][j]){
The error message is:
Unhandled exception at 0x012875DD in CCLC.exe: 0xC0000005: Access
violation reading location 0x0000004B.
SetZero::setZero((int **)a, 4, 5)
a is not an array of pointers, it is simply a 2 dimensional array.
notice how the access violation is reading address 0x0000004B? that's 75, a number between 0 and 99 :) because you are treating a 2 dimensional array (which is just a one dimensional array with a neat way of accessing it) as an array of arrays, it is taking one of the values in your array (75) to be the address of a sub array, then trying to read the non existent array at address 75 (or 0x0000004B)
I suggest that you 'flatten' your arrays and work with them as one dimensional arrays, which I find simpler:
void SetZero::setZero(int * a, int m, int n){
int i, j, k;
int * b = new int [m*n]; //flags to identify whether set to zero or not.
for(i = 0; i < m; i++){
b[i] = new int[n];
for(j = 0; j < n; j++)
b[i*n+j] = 1;
}
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
if(a[i*n+j] == 0 && b[i*n+j]){//DUMP here. If I change it to (a+i)[j], then works.
for (k = 0; k < n; k++){
a[i*n+k] = 0;//but there is NO dump here. Weird!
b[i*n+k] = 0;
}
for(k = 0; k < m; k++){
a[k*n+j] = 0;
b[k*n+j] = 0;
}
j = n;//break. next row loop.
}
delete[] b;
}
int main(){
int a[4*5];
srand(time(NULL));
for(int i = 0; i < 4; i++){//create an 2D array
for(int j = 0; j < 5; j++){
a[i*5+j] = rand() % 100;
cout << a[i*5+j] << " ";
}
cout << endl;
}
SetZero::setZero(a, 4, 5);//type cast.
cout << endl;
for(int i = 0; i < 4; i++){//print result
for(int j = 0; j < 5; j++)
cout << a[i*5+j] << " ";
cout << endl;
}
return 0;
}
One suggestion about the SetZero(). There is a function called memset() which allows you to set all bytes to a specific value given a starting pointer and the range. This function could make your SetZero() function more cleaner:
void * memset ( void * ptr, int value, size_t num );
Fill block of memory. Sets the first num bytes of the block of memory pointed by ptr to the specified value (interpreted as an unsigned char).
Parameters
ptr: Pointer to the block of memory to fill.
value: Value to be set. The value is passed as an int, but the function fills the block of memory using the unsigned char conversion of this value.
num: Number of bytes to be set to the value, size_t is an unsigned integral type.
For example, the following code block from your program:
for (k = 0; k < n; k++){
a[i][k] = 0;//but there is NO dump here. Weird!
b[i][k] = 0;
}
can be achieved by memset in a cleaner way:
memset(a[i], 0, n * sizeof(int));
memset(b[i], 0, n * sizeof(int));