Search code examples
c++arraysdynamic-memory-allocation

How to free subarray's mem which is part of bigger array


I have some trouble with dynamic memory deletion. I have array of 100 integers, but later in runtime more than the half of the array is not used, so i want to free that memory. Here is my attempt. Can anybody explain why i get an error? Thanks!

void dynSybarrDel(){
    int* intArr = new int[100];
    int* subArr = (intArr + 50);
    delete subArr;
}

Solution

  • However if you malloc the memory, you could remove to the end with realloc:

    #include  <cstring>
    void dynSybarrDel(){
        int* intArr = (int*)malloc(100 * sizeof(int));
        int* subArr = (intArr + 50);
        intArr = realloc(intArr, (subArr - intArr)*sizeof(int));
    };
    

    Edit

    To initialize an array-element of specific type in mallocated memory just do this (however you needn't do this on int or other builtin types, when you know that it is overwritten before read, else there would be random values):

    new(elementPtr) myType("parameter1", 2.0);
    

    And to destroy:

    elementPtr->~myType();
    

    elementPtr is just the adress of an element by iteration like this:

    MyType* elementPtr = myArr;
    for(int i = arrSize; i; --i, ++elementPtr)
    

    However if you can use std::vector it allows you more things to do:

    #include <vector>
    
    void dynSybarrDel(){
        std::vector<int> intArr(100);
        auto subArr = intArr.begin() + 50;
        intArr.erase(subArr, intArr.end());
    };
    

    You could even remove a part inside the vector:

    #include <vector>
    #include <numeric>
    
    int main() {
        std::vector<int> intArr(10);
        std::iota(intArr.begin(), intArr.end(), 0); // linear counting [0, 10)
    
        for(int i: intArr) {
            std::cout << i << ' ';
        };
        std::cout << '\n';
        
        auto eraseMeBegin = intArr.begin() + 3;
        auto eraseMeEnd   = intArr.end() - 2;
    
        intArr.erase(eraseMeBegin, eraseMeEnd);
    
        for(int i: intArr) {
            std::cout << i << ' ';
        };
        std::cout << '\n';
    };
    

    Produced output:

    0 1 2 3 4 5 6 7 8 9

    0 1 2 8 9