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