Home > OS >  C Memory leak error when resizing C dynamic array
C Memory leak error when resizing C dynamic array

Time:02-04

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;

}

CodePudding user response:

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.)

  • Related