上級 › ローカル変数への参照を返すとSegmentation faultになる原因 › パターン4
ローカル変数への参照を返すとSegmentation faultになる原因
関数のローカル変数への参照を関数の外に返してしまうバグです。
1 #include <iostream> 2 int& getCount() { 3 __________ c = 3; ^ 4 return c; 5 } 6 int fill2() { 7 int arr[8] = {1,2,3,4,5,6,7,8}; 8 return arr[0]; 9 } 10 int main() { 11 int& r = getCount(); 12 fill2(); 13 std::cout << r << std::endl; 14 return 0; 15 }
Segmentation fault
空欄を埋めてコンパイル・実行を通す
cをstaticにしないと、関数を抜けた時点で無効な参照を返すことになります。
次の問題