-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalloc_Cpp_new_delete.cpp
90 lines (86 loc) · 2.22 KB
/
alloc_Cpp_new_delete.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
* Purpose: massima dimensione per allocazione dinamica della memoria
* Author: Emanuele Rizzolo
* Class: 3XIN
* Date: 2020/03/04
* Note: tecnica "dicotomica" in [0..SIZE_MAX)
*/
#include <cstdio>
#include <cstdint>
// for nothrow
#include <new>
using namespace std;
#define DEBUG 1
void debug(const char *format, size_t data)
{
if (DEBUG)
{
printf(format, data);
}
}
// try to allocate and use size bytes of uninitialized memory
// returns number of usage failures, -1 on allocation failure
size_t test(size_t size)
{
char *a = new (nothrow) char[size]; // try allocation
/*
char *a = nullptr;
try
{
a = new char[size]; // try allocation
}
catch (const std::bad_alloc &e)
{
}
*/
if (a != nullptr) // check success / failure
{
debug("Successfully allocated %zu bytes. Testing ...", size);
size_t nErrors = 0; // numer of errors so far
// check usability setting / getting some bytes
for (size_t index = size - 1; index > 0; index >>= 1)
{
a[index] = 42;
if (a[index] != 42)
{
if (nErrors++ == 0)
{
debug("Error for a[%zu]", index);
}
}
}
debug(nErrors == 0 ? "success\n" : " failure [%zu errors]\n", nErrors);
delete[] a; // free allocated memory
return nErrors;
}
else
{
debug("Unable to allocate %zu bytes.\n", size);
return -1;
}
}
int main(void)
{
debug("SIZE_MAX = %zu\n", SIZE_MAX); // maximum value of a size_t
// find minimum size we can NOT allocate
// search in [0..SIZE_MAX)
size_t begin = 0, end = SIZE_MAX;
size_t count = end - begin;
while (count > 0)
{
size_t step = count / 2;
size_t middle = begin + step;
if (test(middle) == 0) // success
{
begin = middle + 1; // search in [middle + 1..end)
count -= step + 1;
}
else
{
count = step; // search in [begin..middle)
}
}
printf("Maximum size successfully allocated: %zu bytes.\n", begin - 1);
// successful termination
return 0;
}