C++: Dynamic memory allocation

Jene Hojin Choi·2021년 7월 12일
0

C++

목록 보기
2/17
post-thumbnail

메모리

  • Static 메모리 : 데이터 영역에 저장되고 지속성이 보장됨.
  • Heap 메모리 : 힙 영역에 저장되고 지속성이 보장되나 프로그래머에의해 꼼꼼한 관리(메모리 해제)가 필요함.
  • Stack 메모리 : 스택 영역에 저장되고 함수를 빠져나가면 자동 소멸됨.
    ※ 정적메모리 = (전역변수, static변수, 지역변수, 매개변수 저장) // 동적메모리 = (프로그램 실행중 생성되고 소멸되는 변수 저장)

Quiz

This program is supposed to write 1 4 9 16 25 36 49 64 81 100, but it
probably does not. What is the program doing that is incorrect?

#include <iostream>
 using namespace std;
 
 // 받은 int로 구성된 array의 모든 element를 제곱해줌
 int* computeSquares(int& n) {
   int arr[10];
   n = 10;
   for (int k = 0; k < n; k++)
   	arr[k] = (k+1) * (k+1);
   return arr;
 }
 
 // 아무것도 안 함 
 void f() {
   int junk[100];
   for (int k = 0; k < 100; k++)
     junk[k] = 123400000 + k;
 }
 
 // 프린트
 int main() {
   int m;
   int* ptr = computeSquares(m);
   f();
   for (int i = 0; i < m; i++)
   	cout << ptr[i] << ' ';
   cout << "\n";
   return 0;
 }

컴파일 결과

결과를 보면 위와 같이 예상했던 1 4 9 16 25 36 49 64 81 100가 아니라, garbage value가 프린트 되는 것을 볼 수 있다.

또한 Address of stack memory associated with local variable 'arr' returned 이라는 경고가 뜬다.

원인

This is undefined behaviour, plain and simple. The only reason it "works" is because with this particular compiler the stack hasn't been trashed yet, but it is living on borrowed time.

The lifetime of arr ends immediately when the function call is complete. After that point any pointers to arr are invalidated and cannot be used.

Your compiler uses stack memory to store local variables, and the warning indicates that you're returning an address to a now-invalidated stack variable.

Solution

The only way to work around this is to allocate memory dynamically and return that:

int arr[10] -> static int arr[10]

0개의 댓글