Commit 5afa692eb38d5a491609824b01ae881085d76dec

Authored by Grzegorz Jabłoński
1 parent 70abbf1e

Replace malloc with aligned_alloc

examples11/04-vectortmpl/makefile
... ... @@ -4,7 +4,7 @@ testvector: testvector.o
4 4 g++ -g -Wall $^ -o $@
5 5  
6 6 testvector.o: testvector.cpp vector.h
7   - g++ -g -c -Wall -pedantic $< -o $@
  7 + g++ -std=c++17 -g -c -Wall -pedantic $< -o $@
8 8  
9 9 opnew: opnew.o
10 10 g++ -g -Wall $^ -o $@
... ...
examples11/04-vectortmpl/vector.h
... ... @@ -22,7 +22,7 @@ public:
22 22  
23 23 cap = round_up_to_power_of_2(s);
24 24  
25   - data = static_cast<C *>(malloc(cap * sizeof(C)));
  25 + data = static_cast<C *>(std::aligned_alloc(alignof(C), cap * sizeof(C)));
26 26 if (!data)
27 27 throw bad_alloc();
28 28 size = s;
... ... @@ -57,7 +57,7 @@ public:
57 57  
58 58 vector(const vector<C> &s) {
59 59 cap = s.cap;
60   - data = static_cast<C *>(malloc(cap * sizeof(C)));
  60 + data = static_cast<C *>(std::aligned_alloc(alignof(C), cap * sizeof(C)));
61 61 if (!data)
62 62 throw bad_alloc();
63 63 size = s.size;
... ... @@ -110,13 +110,13 @@ public:
110 110 if (cap > std::numeric_limits<decltype(size)>::max() / 2)
111 111 throw bad_alloc();
112 112 unsigned int newcap = (cap == 0) ? 1 : 2 * cap;
113   - C *newdata = static_cast<C *>(malloc(newcap * sizeof(C)));
  113 + C *newdata = static_cast<C *>(std::aligned_alloc(alignof(C), newcap * sizeof(C)));
114 114 if (!newdata)
115 115 throw bad_alloc();
116 116 unsigned i;
117 117 try {
118 118 for (i = 0; i < size; i++)
119   - new (newdata + i) C(data[i]);
  119 + new (newdata + i) C(std::move(data[i]));
120 120 } catch (...) {
121 121 for (unsigned j = 0; j < i; ++j)
122 122 (newdata + j)->~C();
... ...