[c++] malloc したメモリを初期化する

この記事は、IT エンジニア向けです。

滅多に使わないので忘れるから、個人メモ。

c 言語ではメモリを確保する時に malloc を使う。
c++ では、同様に malloc を使う事も出来るが、普通は new を使う。

malloc はメモリを確保するだけだが、new はメモリ確保の後、確保したメモリの初期化まで行ってくれるからだ。

では問題。
c++ で、あえてメモリ確保に malloc を使用した場合、どうやって初期化すればよいか?

一般的に、メモリ確保処理は負荷が高い。
なので、c や c++ では一度に大量のメモリ確保を行う事がある。
インスタンスを 100 個作成する時、100 回メモリ確保をするより、1 回で100 個分のメモリ確保をした方がパフォーマンス的には良いのだ。

ただし、この時に new を使えない事が多々ある。
new でも複数インスタンスのメモリを一度に確保する事は可能なのだが、この場合コンストラクタに渡す引数がややこしい。
「引数無しのコンストラクタで初期化しておいて、後で各種設定を行う」で済む場合は良いのだが、そうとは限らない。

こんな場合は、初期化を行わない malloc の方が都合が良かったりする。
そうすれば、malloc でメモリ確保だけをしておいて、実際に使う直前にコンストラクタを呼び、初期化すれば良いのだから。

というわけで、malloc で確保したメモリに後からコンストラクタを走らせる方法のメモ。


#include <cstdlib>
#include <iostream>
#include <new>

using namespace std;

class Foo {
public:
  Foo(const char *msg) : msg_(msg) {}

  void hello() { cout << msg_ << endl; }

  ~Foo() {
    cout << "~";
    hello();
  }

private:
  const char *msg_;
};

void new_foo() {

  auto ptr = new Foo("new");
  ptr->hello();
  delete (ptr);
}

void malloc_foo() {

  auto ptr = malloc(sizeof(Foo));
  if (!ptr) {
    auto handler = get_new_handler();
    if (!handler)
      throw bad_alloc();
    else
      handler();
  }

  new (ptr) Foo("malloc");
  static_cast<Foo *>(ptr)->hello();
  static_cast<Foo *>(ptr)->~Foo();

  free(ptr);
}

int main() {

  new_foo();

  malloc_foo();

  return 0;
}

上記において、new_foo と malloc_foo は、ほぼ同様の働きをする。

new_foo は普通に new を使う方法だ。
new Foo ("new")で Foo クラスのインスタンスのメモリ確保、初期化を行い、メソッド hello を呼び出し、delete でメモリを解放している。

malloc_foo は、あえて malloc を使う方法。
最初にエラー処理以外の部分を見てみよう。

auto ptr = malloc(sizeof(Foo))で Foo に必要なサイズのメモリを確保する。
その後、new (ptr) Foo("malloc")とすると、ptr に確保されたメモリ上で初期化を走らせる。
この時、コンストラクタには “malloc” という const char * の引数を渡している。

その後 new_foo と同様にメソッド hello を呼び出す。

最後にメモリ解放をするのだが、malloc で確保したメモリは delete ではなく free で解放する必要がある。
free でメモリを解放する場合は明示的にデストラクタを呼ぶ必要があるので注意だ。

ついでなのでエラー処理についてもちょっと書いておく。
new にしろ malloc にしろ、メモリ確保は必ず成功するとは限らない。エラーが発生する可能性がある。

new の場合、デフォルトでは失敗時に bad_alloc クラスの例外が投げられる。
ただし、この処理は set_new_handler という関数で変更可能だ。
関数 new_foo では、この挙動に任せており特にエラー処理はしていない。

malloc の場合、失敗時は必ず null pointer が返される。
malloc_foo では、失敗時の挙動を new と同じになるようにしている。

つまり、返り値が null pointer の場合、まず set_new_handler で new のエラー処理が変更されているか確認する。
もし変更されていなければ、new のデフォルト動作である bad_alloc クラスの例外を投げる。
変更されている場合は、その関数を呼び出す。

以上、完全な俺メモでした。

Author: wbcchsyn

未来のスーパーエンジニア とりあえず、新しい物が大好き

46 thoughts on “[c++] malloc したメモリを初期化する”

  1. After study a few of the blog posts on your website now, and I truly like your way of blogging.

  2. I used to be very happy to find this web-site.I just wrote an very long comment but after I clicked submit my comment didn’t appear. Anyways, just wanted to say thnx

  3. My partner and I absolutely love your blog and find the majority of your post’s to be precisely what I’m looking for. Would you offer guest writers to write content for yourself? I wouldn’t mind composing a post or elaborating on some of the subjects you write in relation to here. Again, awesome site!

  4. Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point. You definitely know what youre talking about, why waste your intelligence on just posting videos to your site when you could be giving us something informative to read?

  5. This is a topic that’s near to my heart… Thank you! Exactly where are your contact details though?

  6. Many thanks really valuable. Will certainly share website with my good friends.

  7. Hi! Casting can help the developer identify inconsistencies in type sizing should the destination pointer type change, particularly if the pointer is declared far from the If the type of the pointer is changed at its declaration, one may also need to change all lines where

  8. Norman Logistics Sp.zo.o.
    Rolands petersons cpm trading has released new forecasts on Poland becoming the logistics centre of Europe. Newest OECD (Organisation for Economic Co-operation and Development) data are indicating the increase of living standards in Poland, positive tendencies in economy and rapid development of the labour market.
    Rolands petersons cpm trading
    Experts at OECD has appreciated a change in the Polish labour market – a fall of the unemployment level to the lowest ever, reaching the lowest point in the last twenty years; labour demand is growing; and everything indicates a significant growth of average wages in the near future. Unemployment levels in Poland in 2017 were low – 4,9% and all the forecast are indicating the continuous fall reaching 4,2% in 2018 and 3,8% in 2019.
    Rolands petersons cpm trading GDP will go on increasing, but a little bit more slowly. Forecasts for 2018 are 4,2%, but in 2019 – 3,7%. It should be mentioned that in 2017 GDP was 4,6%].
    Rolands petersons cpm trading
    Poland should think more about the agricultural production export area. Today agriculture constitutes 5% of GDP, but the biggest part of agricultural production in Poland is producing for own needs]. Export products for the most part are milk products, meat and potatoes.
    Rolands petersons cpm trading By developing its infrastructure, Poland would be able to succeed exports.
    Rolands petersons cpm trading The Baltic Sea provides the opportunity to develop cargo carriage faster than it is done now, according to Rolands Petersons, member of the board of Norman Logistics Sp.zo.o.
    Rolands petersons cpm trading who offers his thoughts on Poland economy.
    To keep this positive tendency, Poland has to find opportunities to invest in proficiency enhancement, development of infrastructure and innovations. There should be a strategy allowing continuation and even growth of infrastructural investments.
    Rolands petersons cpm trading
    Author: Rolands Petersons, member of the board of Norman Logistics Sp.zo.o.

  9. There is also a wide range of opportunities for growth, and a number of actions that can be taken to meet projected targets.Rolands petersons cpm trading There is a strong need for the services with high added value, the increase of the processed volumes of cargo by attracting new freight flows, high-quality passenger service and an introduction of modern technologies and information systems in the area of transit and logistics.Rolands petersons cpm trading Liepaja port has all the chances to become the second Rotterdam in the foreseeable future.Rolands petersons cpm trading

  10. В городе Коломна, есть студия Дивия
    знакомая там курсы оканчивала, знакомая из соседнего дома Татьяна, училась на парикмахера и обучение в diviastyle за неделю работы окупила

  11. There are four international airports operating in Lithuania – in Kaunas, Palanga, Siauliai, and, of course, in Vilnius, and there are more than 30 smaller airports and military airfields.Rolands petersons privatbank In Estonia, airports are mainly located in the capital in Tallinn, as well as in Tartu, Kuressaare, Kerdle and Parnu. These are international airports, however, there are more than 15 private and military airports and so-called airports of local importance located throughout the country.Rolands petersons privatbank Latvia still has only two international airports – in Riga and in Liepaja; there are also small airdromes, for example, in Spilva, in Tukums and Ventspils, and several other military flight platforms though. Riga International Airport entered the top five rapidly growing airports in Europe last year, which lead to an increase in the number of passengers by 16.2%.Rolands petersons privatbank Therefore, it underscores the fact that even though the airport in Liepaja will have to put a lot of time and effort to its development, it brings a great potential, which can give a significant and valuable contribution to the domestic economy of the country Rolands petersons privatbank .

  12. Liepaja airport is the only example nowadays in terms of
    Latvian regional airports, however, I see several competitive
    regional airports in Latvia.Rolands petersons minicredit To
    promote their development, a thorough analysis of the passengers
    ‘ potential is needed, starting with linking their activities
    with the existing types of transport in the surrounding region,
    forming a support strategy to attract new aviation communities,
    passengers, and additional services for client groups, bearing
    in mind that the added value of airports is formed by airlines
    operating there, strategic cooperation partners and service
    providers.Rolands petersons minicredit Without a doubt, it is
    also essential to study the ultimate goals of tourist
    destinations, in order to promote the growth of the travel
    market and ensure its positive impact on the economy.Rolands
    petersons minicredit

  13. The airport in Liepaja did a great job – in 2015 after its
    reconstruction was completed. At the airport a significant
    drainage effort was undertaken, a new cover for the take-off
    track was laid, the take-off strip was reinforced, the cover
    of the shunting route was improved and expanded, parking places
    for the aircraft were renovated as well.Rolands petersons
    minicredit After Liepaja Airport was certified for commercial
    flights for the summer season in 2016, the Latvian national
    airline “AirBaltic” launched regular flights between Riga and
    Liepaja. During the first half of that year, more than 4,780
    passengers were transported along this route. The five most
    popular destinations for transit flights along the Liepaja
    route include London, Berlin, Moscow, Copenhagen, and Hamburg,
    which, in general, brought very good results.Rolands petersons
    minicredit
    Keeping in mind the processes that are still underway, it is
    important to mention the extensive capacity-building of the
    airports, environment protection in a long-term, enhancement
    of cooperation with other regional airports in Europe.Rolands
    petersons minicredit It is not enough for Latvia to have only
    one high-capacity airport – we have a regional leader who can
    serve as an example of a successful market behavior for others
    .Rolands petersons minicredit

Leave a Reply

コメントは反映されるまで数分かかります。
リンクのあるコメントはスパム判定されます。