Home > Software engineering >  C malloc(): corrupted top size on loop
C malloc(): corrupted top size on loop

Time:02-20

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

CodePudding user response:

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.

  • Related