Rustにおける構造体のデータ格納場所分析

概要 このページで「String構造体もスタックに入りますが、ヒープに入るデータの参照アドレスが一つ入ります。」とあった。 分析することで確認する。 GDBを用いて分析する。 筆者はWindows11においてWSLを用いてUbuntu24.04を使用している。 2025年11月1日現在、筆者の環境ではGDBは以下のコマンドでインストールできる。 sudo apt install gdb 分析 本稿では、前述のページにあるサンプルコードに対して分析を行う。リンク切れをしたときに備えて、対象にするソースコードを示しておく。 以下の文章では、ソースコードといったら、以下のRustコードのことを指すものとする。 struct SeaCreature { animal_type: String, name: String, arms: i32, legs: i32, weapon: String, } fn main() { // SeaCreatureのデータはスタックに入ります。 let ferris = SeaCreature { // String構造体もスタックに入りますが、 // ヒープに入るデータの参照アドレスが一つ入ります。 animal_type: String::from("crab"), name: String::from("Ferris"), arms: 2, legs: 4, weapon: String::from("claw"), }; let sarah = SeaCreature { animal_type: String::from("octopus"), name: String::from("Sarah"), arms: 8, legs: 0, weapon: String::from("none"), }; println!( "{} is a {}. They have {} arms, {} legs, and a {} weapon", ferris.name, ferris.animal_type, ferris.arms, ferris.legs, ferris.weapon ); println!( "{} is a {}. They have {} arms, and {} legs. They have no weapon..", sarah.name, sarah.animal_type, sarah.arms, sarah.legs ); } 構造体のインスタンスとなる変数の場所 ソースコードにおける、main関数の中で定義されているferrisとsarahはSeaCreature構造体のインスタンスである。 これはメモリ上どこにあるのだろうか? ...

2026年5月2日