Is there a way to free only part of a dynamically allocated array in C \ C ++ (compress an existing array)?

In the program, I select a huge multidimensional array, make some number-crunch, then only the first part of this array is of additional interest, and I would like to free only part of the array and continue to work with the data in the first part. I tried using realloc, but I'm not sure if this is correct, given that I have to save the data in an array and preferably avoid copying this fragment in memory.

#include <cstring>
#include <cassert>
#include <iostream>

using namespace std;

void FillArrayThenTruncate(char* my_array, const int old_size, int* new_size);

int main() {
    const int initial_size = 1024*1024*1024;
    char* my_array = static_cast<char*>(malloc(initial_size));
    assert(my_array);
    int new_size;
    FillArrayThenTruncate(my_array, initial_size, &new_size);
    for(int i = 0; i < new_size; ++i) cout << static_cast<int>(my_array[i]) << endl;
}

void FillArrayThenTruncate(char* my_array, const int old_size, int* new_size) {
    //do something with my_array:
    memset(my_array, 0, old_size);
    for(int i = 0; i < 10; ++i) my_array[i] = i % 3;
    //cut the initial array
    *new_size = 10;
    void* new_array = realloc(my_array, *new_size);
    cout << "Old array pointer: " << static_cast<void*>(my_array) << endl;
    cout << "New array pointer: " << new_array << endl;
    my_array = static_cast<char*>(new_array);
    assert(my_array != NULL);
}

UPDATE:
* Please do not bother offering STL. Question about array C.
* Thanks to "R Samuel Klatchko" for pointing out the error in the code above.

+3
3

, malloc, realloc.

realloc , :

// Only valid when shrinking memory
my_array = realloc(my_array, *new_size);

: , , realloc NULL, my_array. .

+2

, ... std::vector STL.

: . , . realloc / , , .

, , . , , .

+4

For C ++, use STL containers instead of manually working with your memory. For C exists realloc().

+3
source

Source: https://habr.com/ru/post/1752584/


All Articles