i have 2 variants of code:
1st:
void PrintMem(const int* memarr,const size_t size) {
for (size_t index = 0; index < size; ++index) {
std::cout << '<'<<(index+1)<<"> "s<<*(memarr + index) << std::endl;
}
}
void FillMem(int* memarr, const size_t size) {
srand(time(0));
for (size_t index = 0; index < size; ++index) {
*(memarr + index) = rand() % 100;
}
}
int main() {
const int size_iter = 10000000;
int n = 30;
int* ptr = nullptr;
int size = size_iter;
for (int i = 1; i <= n; ++i) {
size = size_iter * i;
if (i == 1) {
ptr = (int*)malloc(size * sizeof(int));
}
else {
ptr = (int*)realloc(ptr, size * sizeof(int));
}
if (ptr == nullptr) {
printf("memory allocation errorn");
break;
}
std::cout << '[' << i << ']';
printf(" address: %p", (void*)ptr);
std::cout << ", size: "s << size;
std::cout << " *********************" << std::endl;
FillMem(ptr, size);
//PrintMem(ptr, size);
}
if (ptr != nullptr) {
free(ptr);
}
}
2nd: (i think is better)
void PrintMem(const int* memarr,const size_t size) {
for (size_t index = 0; index < size; ++index) {
std::cout << '<'<<(index+1)<<"> "s<<*(memarr + index) << std::endl;
}
}
void FillMem(int* memarr, const size_t size) {
srand(time(0));
for (size_t index = 0; index < size; ++index) {
*(memarr + index) = rand() % 100;
}
}
int main() {
const int size_iter = 10000000;
int n = 30;
int* ptr = nullptr;
int size = size_iter;
for (int i = 1; i <= n; ++i) {
size = size_iter * i;
int* new_ptr = nullptr;
if (i == 1) {
new_ptr = (int*)malloc(size * sizeof(int));
}
else {
new_ptr = (int*)realloc(ptr, size * sizeof(int));
}
if (new_ptr == nullptr) {
printf("memory allocation errorn");
break;
}
ptr = new_ptr;
std::cout << '[' << i << ']';
printf(" address: %p", (void*)ptr);
std::cout << ", size: "s << size;
std::cout << " *********************" << std::endl;
FillMem(ptr, size);
//PrintMem(ptr, size);
}
if (ptr != nullptr) {
free(ptr);
}
}
how will be correct to free memory?
if (ptr != nullptr) {
free(ptr);
}
or
if (ptr != nullptr) {
for (int i = 0; i < size; ++i) {
free((ptr + i));
}
free(ptr);
}
tried all of these variants.
2nd variant with int* new_ptr i think will be better because if will keep at least previous iteration of memory resize
just need to know how to optimize this and is that correct to free only ptr or i need to free each memory block?
New contributor
vansergh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.