How to fix 'Invalid Pointer' when merging two C++ Arrays - c++

My goal in this program is to take two user entered arrays of a given size and merge them into one.
I'm able to successfully enter both arrays' size and their elements, but it fails to output the merged array- giving me this error:
"Error in `./a.out': free(): invalid pointer: 0x0..."
I've tried to debug but to no avail, I can't seem to figure out if I have incorrect syntax or I'm making an incorrect call.
Any help appreciated
#include<iostream>
using namespace std;
int* mergeArrays(int[], int[], int, int);
int arr1[0], arr2[0];
int main()
{
int size1, size2, i;
cout<<"Enter the first array's size : ";
cin>>size1;
int *arr1 = new int[size1];
cout<<"Enter the first array's elements : ";
for(i=0; i<size1; i++)
{
cin>>arr1[i];
}
cout<<"Enter the second array's size : ";
cin>>size2;
cout<<"Enter the second array's elements : ";
for(i=0; i<size2; i++)
{
cin>>arr2[i];
}
delete[] arr1;
delete[] arr2;
cout << mergeArrays;
}
int* mergeArrays(int arr1[], int arr2[], int size1, int size2){
int i, k, size;
int size3 = size1 + size2;
int *mergeArr = new int[size3];
for(i=0; i<size1; i++)
{
mergeArr[i]=arr1[i];
}
size=size1+size2;
for(i=0, k=size1; k<size && i<size2; i++, k++)
{
mergeArr[i]=arr2[i];
}
cout<<"The merged array is: \n";
for(i=0; i<size3; i++)
{
cout<<mergeArr[i]<<" ";
}
return mergeArr;
}

Your program exhibits undefined behavior, by way of a buffer overrun. arr2 is an array of zero size, arr2[i] is accessing out of bounds for any value of i.
Also, you call delete[] arr2 but arr2 was not allocated with new

Related

C++ malloc(): corrupted top size on loop

I'm trying to create a function printarr that prints a dynamically sized array. However, whenever I try to run the code I get the error above. I tried copying code I found online as well, but get the same error, so I'm wondering if there's something wrong with my installation, or another part of the code is somehow affecting it. The entire thing seems super simple, which makes me even more stumped. Here's the code:
#include <iostream>
using namespace std;
//Generates an array with k inversions of size n
int* generate_k_inversion(int k, int n){
int *arr=new int(n);
//Check if number of inversions is possible
if(k>(n*(n-1)/2)){
cout<<"Impossible number of inversions!";
throw(-1);
}
//Loop to generate points
for(int i=0;i < n;i++){
arr[i]=i;
}
//Loop to invert
return arr;
}
//Copies dynamic arrays of size n
int* copy(int* arr1,int n){
int* arr2=new int(n);
for(int i=0;i<n;i++){
arr2[i]=arr1[i];
}
return(arr2);
}
//Generates output of best and worst cases of bubble and insertion sort in integers of size n
void test1(int n){
//generate best case
int *arrb1=generate_k_inversion(0,n);
int *arrb2=copy(arrb2,n);
delete [] arrb1;
delete [] arrb2;
//generate worst case
int *arrw1=generate_k_inversion((n*(n-1)/2),n);
int *arrw2=copy(arrw2,n);
delete [] arrw1;
delete [] arrw2;
}
//Prints a dynamic array arr of size n
void printarr(int* arr, int n)
{
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
}
//Just initialize both tests
int main(){
int size=10;
int* arr1=generate_k_inversion(0,size);
printarr(arr1,size);
delete [] arr1;
}
Thanks for the help
The line
int *arr=new int(n);
will allocate memory for a single int and initialize that int to n.
Therefore, the loop
for(int i=0;i < n;i++){
arr[i]=i;
}
will access arr out of bounds, causing undefined behavior.
What you probably want is to write
int *arr=new int[n];
instead, which will allocate memory for n values of type int.

(C++) How to dynamic array parameters?

I use stackoverflow for the first time.
Error Question 1. I changed n or 4, 16 etc.. result = compile error
Error Question 2. It is not possible to call '2 Dimensional Array' with 'User Defined Function'.
Sorry for the incorrect grammar.
void outputarr(int n, int (*arr)[**n**]){ //n error
...
}
void inputarr(int n, int (*arr)[**n**]){ //n error
...
}
int main(void){
int input;
int *input2;
cin >> input;
cout << "Length of Array : " << input << '\n';
input2 = &input;
int **arr = new int*[input];
for(int i=0; i<input; i++)
arr[i]= new int[input];
**inputarr(input, arr); // pass to input&output error
outputarr(input, arr);** // pass to input&output error
for(int i=0; i<input; i++)
delete[] arr[i];
delete[] arr;
return 0;
}

returning an array address from function in c++ issue

i'm new to programming , this code gives me syntax error in line => int *result = apply_all(array1,5,array2,3) this is the error: expected primary-expression before '}' token|
i'm trying to write function called apply_all expects 2 arrays of integers and their sizes and dynamically allocates a new array of integers whose size is the product of 2 array sizes.
the function should loop through the 2nd array and multiple each element accross each element of array 1 and store the product in newly created array. the function is returning a pointer of to the newly allocated array.
also i wrote a function which is print to display the 1st & 2nd & newly array.
#include <iostream>
using namespace std;
//function prototype
int *apply_all(int *array1 ,int size1,int *array2,int size2);
void print(int *array,int size);
int main()
{
int array1[] {1,2,3,4,5};
int array2[] {10,20,30};
cout << "Array 1:";
print(array1,5);
cout << "Array 2:";
print(array2,3);
int *result = apply_all(array1,5,array2,3);
cout << "Result : ";
print(result,15);
delete [] result;
return 0;
}
int *apply_all(int *array1 ,int size1,int *array2,int size2)
{
int *result {nullptr};
result = new int[size1 * size2];
for (int i{0};i<size2;i++)
for(int j{0};j<size1;j++)
*(result[i*5+j]) = *(array1[i])**(array2[j]);
return result;
}
void print(int *array,int size)
{
for(auto num:array)
cout << num << endl;
}
On this line:
*(result[i*5+j]) = *(array1[i])**(array2[j]);
since result[i*5+j] gives you an int, you are trying to dereference an int, which is not possible.
You just need to do:
result[i*5+j] = array1[i] * array2[j];
Also, in print, your range-for loop won't work with a pointer. You need to do:
for(int i = 0; i < size; ++i)
cout << array[i] << endl;
Also, in apply_all, your loop bounds are incorrect. i needs to go till size1, and j needs to go to size2.
Here's a demo.
Since you are new, a simple work around would be creating an array with buffer space to store your results in and passing the pointer for this into apply_all. You could then write to this array which (being declared in main) should be very easy to access and cause few errors and use a c-string like ending to know when your results are over and to stop printing from the array (c-strings end with a value of 0 so that programs don't read unrelated memory). eg:
int buf[99];
apply_all(array_1, size1, array_2, size2, buf, size3);
for (int x = 0; buf[x] != end of buf var; x++;)
{
print(buf[x])
}
and
apply_all()
{
buf[start-end] = whatever you want;
buf[end + 1] = some variable that won't appear in buffer; //max int size?
}

I am trying to pass an DMA array and its size as an argument but it is giving an error

I am trying to pass a dynamic memory allocated array and its size to a function 'sum' but it is giving error of permissive what should I do?
#include<conio.h>
#include<iostream>
using namespace std;
int sum(int n[], int *m)
{
for(int z=0;z<*m;z++)
{
cout<<"\n the output is = "<<n[z]<<"\n";
}
}
int main()
{
int *n,*m,a; //declaration is done here**strong text**
cout<<"enter the size of array = ";
m=new int;
cin>>*m;
n=new int[*m];
for(int i=0;i<*m;i++)
{
cout<<"\n enter the "<<i+1<<" array = ";
cin>>n[i];
cout<<"\n";
}
/* for(int z=0;z<*m;z++)
{
cout<<"\n the output is = "<<n[z]<<"\n";
}*/
int sum(n,&m);//here "m" is an pointer and I am trying to pass int in a function with an array
return 0;
}
Your code should, probably, look like the following (Linux Ubuntu + gcc):
#include <iostream>
using namespace std;
int sum(int n[], int m)
{
int s=0;
for(int z=0; z<m; z++)
{
cout<<"\n array["<<z<<"]= "<<n[z]<<"\n";
s+=n[z];
}
return s;
}
int main()
{
int *n,m;
cout<<"enter the size of array = ";
cin>>m;
n=new int[m];
for(int i=0; i<m; i++)
{
cout<<"\n enter array["<<i+1<<"] value = ";
cin>>n[i];
cout<<"\n";
}
int s = sum(n, m);
cout<<"s="<<s<<endl;
return 0;
}
There is no use allocating the size of the array m dynamically. It is an ordinary int variable and can be initialized as
cin>>m;
You may also write the sum prototype in the form
int sum(int * n, int m)
It is another way of passing a 1-dimensional array as a function parameter.
Speaking frankly, these questions are the very basics of the language.
You should, probably, read something like
Dynamic memory allocation/dynamic arrays
about dynamic memory allocation and dynamic arrays and
Simple cases of std::cin usage
about the simplest cases of std::cin usage in C++.

My code runs fine when I debug it, but crashes as soon as I run it

I have been asked to built a K sorted array by my professor and then sort it using minheap. A k sorted array is basically an array where each element is at most K positions away from the location it would be if the array was fully sorted in ascending order. For instance, if K=3, the element at position i=8 can be at locations 5, 6, 7, 8, 9, 10, or 11 in the fully sorted arrayI'm stuck in the first part of the problem.
Requirements:
Allow the user to enter a number of (N) elements and the number K.
Produce a K-sorted array based on the user input (more than one K-sorted array can be produced; randomly pick one). Display it.
After rigorous thinking I built the below code for K Sorting:
void kSortedArray:: displayKSorted()
{
cout<<"Please enter the no. of elements you want to KSort: ";
cin>>N;
cout<<"Please enter the value for K: ";
cin>>K;
int i=0;
while (i<N)
{
cout<<"Enter element "<<i+1<<" : ";
cin>>arr[i++];
}
insertion_sort(arr,N);
srand(time(NULL));
int output=0;
i=0;
int maxRand=0;
int minRand=0;
int arr2[N];
int a=0;
int found=0;
int found1=0;
int range=0;
int count1=0;
vector<int>:: iterator it1;
vector<int>:: iterator it2;
vector<int> arr3;
while(kSortedIndex.size()<N)
{
minRand=range-K;
maxRand=range+K;
output = minRand + (rand() % (maxRand - minRand + 1));
if (output<0)
{
output=N+output;
}
if(output>N-1)
{
output=output-N;
}
//arr2[i]=output;
for(it1=kSortedIndex.begin();it1!=kSortedIndex.end();it1++)
{
if(*it1==output)
{
found=1;
for(it2=arr3.begin();it2!=arr3.end();it2++)
{
if(*it2==output)
{
found1=1;
break;
}
}
if(found1==0)
{
arr3.push_back(output);
count1++;
}
break;
}
}
if(found==0)
{
kSortedIndex.push_back(output);
count1=0;
arr3.clear();
range++;
}
found=0;
found1=0;
if (count1>((2*K)+1))
{
range--;
count1=0;
}
if(range>(N-1))
range--;
}
vector<int>::iterator it;
int j=0;
// i=0;
for(it=kSortedIndex.begin();it!=kSortedIndex.end();it++)
{
arr2[*it]=arr[j];
j++;
//cout<<arr2[j++];
}
for(j=0;j<N;j++)
{
cout<<arr2[j];
}
}
Below is the header file:
class kSortedArray
{
public:
kSortedArray();
void displayKSorted();
protected:
private:
int N=0;
int K=0;
int* arr=new int [N];
createKSorted();
void insertion_sort(int arr[],int length);
vector <int> kSortedIndex;
};
Could someone please help me to figure out why my code crashes when I run it and runs fine when I debug it. Is it a memory leak issue? I even tried deleting arr, arr2 and clearing arr3 but that isn't working (code still cashes). Your help much appreciated.
The declaration int* arr=new int [N]; in the header is wrong. You cannot allocate memory for the array here because you do not yet know the value for N. That value will be known only after cin>>N; in the kSortedArray:: displayKSorted function. Therefore you need to do allocate memory there:
void kSortedArray:: displayKSorted()
{
cout<<"Please enter the no. of elements you want to KSort: ";
cin>>N;
arr = new int [N]; // <<< add this line
cout<<"Please enter the value for K: ";
cin>>K;
int i=0;
...
Header:
...
private:
int N=0;
int K=0;
int* arr; // =new int [N]; <<< remove the allocation
createKSorted();
void insertion_sort(int arr[],int length);
...
Disclaimer: This is non tested non error checking code, and there may be more problems.