調べようと思ったきっかけは、golang では以下のように ローカル変数のアドレスを戻り値としても問題ないということ。 package main import ( "fmt" ) type Animal struct { Name string Age int } func main() { animal := allocAnimal() fmt.Printf("allocate animal structure %p", animal) } func allocAnimal() *Animal { return &Animal{} } C/C++ ではローカル変数のポインタを戻り値とした場合、 スタック領域のポインタを関数外に渡してしまうため、コンパイル時点で警告が表示されます (なぜエラーにしない) 実行時には最悪、セグメンテーションフォールトで落ちます そのため、malloc や n
![golangではスタックとヒープを気にする必要が無い](https://cdn-ak-scissors.b.st-hatena.com/image/square/19d20bbd1535a294866b8265d5e3634a315c4561/height=288;version=1;width=512/https%3A%2F%2Fres.cloudinary.com%2Fzenn%2Fimage%2Fupload%2Fs--0lO84WCX--%2Fc_fit%252Cg_north_west%252Cl_text%3Anotosansjp-medium.otf_55%3Agolang%2525E3%252581%2525A7%2525E3%252581%2525AF%2525E3%252582%2525B9%2525E3%252582%2525BF%2525E3%252583%252583%2525E3%252582%2525AF%2525E3%252581%2525A8%2525E3%252583%252592%2525E3%252583%2525BC%2525E3%252583%252597%2525E3%252582%252592%2525E6%2525B0%252597%2525E3%252581%2525AB%2525E3%252581%252599%2525E3%252582%25258B%2525E5%2525BF%252585%2525E8%2525A6%252581%2525E3%252581%25258C%2525E7%252584%2525A1%2525E3%252581%252584%252Cw_1010%252Cx_90%252Cy_100%2Fg_south_west%252Cl_text%3Anotosansjp-medium.otf_37%3Arookxx%252Cx_203%252Cy_121%2Fg_south_west%252Ch_90%252Cl_fetch%3AaHR0cHM6Ly9zdG9yYWdlLmdvb2dsZWFwaXMuY29tL3plbm4tdXNlci11cGxvYWQvYXZhdGFyLzA1NmI4MTMwNWQuanBlZw%3D%3D%252Cr_max%252Cw_90%252Cx_87%252Cy_95%2Fv1627283836%2Fdefault%2Fog-base-w1200-v2.png)