C++ realloc_01
Date: 2023-02-07Last modified: 2024-11-02
Table of contents
int *ptr1 = nullptr;
int *ptr2 = nullptr;
auto printPointers = [&](int sz, string title) {
fmt::print("\n{:14} ptr1|{:14} ptr2|{}\n", static_cast<void *>(ptr1),
static_cast<void *>(ptr2), title);
for (int i = 0; i < sz; ++i) {
fmt::print("{},", ptr2[i]);
}
};
printPointers(0, "Initial null");
ptr2 = (int *)realloc(ptr1, sizeof(int));
printPointers(1, "First realloc (non initilized value on memory)");
// Realloc will copy the previous memory content
for (auto i = 1; i <= 64; ++i) {
ptr2 = (int *)realloc(ptr1, i * sizeof(int));
if (ptr2) {
ptr1 = ptr2;
ptr2[i - 1] = (i - 1) % 10; // initilize the i-th position
if (i % 4 == 0) {
printPointers(i, fmt::format("Realloc {} x sizeof(int)", i));
}
} else {
fmt::print("Failure on realloc\n");
break;
}
}
free(ptr2);
// the pointer address remains the same
// the content is destroyed
printPointers(4, "After free ptr2" );
ptr1 = ptr2 = nullptr;
printPointers(0, "After nullptr attribution" );
Possible output
0x0 ptr1| 0x0 ptr2|Initial null
0x0 ptr1|0x55e61d0cc8c0 ptr2|First realloc (non initilized value on memory)
0,
0x55e61d0cc920 ptr1|0x55e61d0cc920 ptr2|Realloc 4 x sizeof(int)
0,1,2,3,
0x55e61d0cc960 ptr1|0x55e61d0cc960 ptr2|Realloc 8 x sizeof(int)
0,1,2,3,4,5,6,7,
0x55e61d0cc960 ptr1|0x55e61d0cc960 ptr2|Realloc 12 x sizeof(int)
0,1,2,3,4,5,6,7,8,9,0,1,
0x55e61d0cc9d0 ptr1|0x55e61d0cc9d0 ptr2|Realloc 16 x sizeof(int)
0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,
0x55e61d0cc9d0 ptr1|0x55e61d0cc9d0 ptr2|Realloc 20 x sizeof(int)
0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,
0x55e61d0cc9d0 ptr1|0x55e61d0cc9d0 ptr2|Realloc 24 x sizeof(int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 x sizeof(int)
0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,
0x55e61d0cc9d0 ptr1|0x55e61d0cc9d0 ptr2|Realloc 60 x sizeof(int)
0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,
0x55e61d0cc9d0 ptr1|0x55e61d0cc9d0 ptr2|Realloc 64 x sizeof(int)
0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,
0x55e61d0cc9d0 ptr1|0x55e61d0cc9d0 ptr2|After free ptr2
1583468748,5,1228791699,863312228,
0x0 ptr1| 0x0 ptr2|After nullptr attribution