Skip to content

Instantly share code, notes, and snippets.

@wooseokyourself
Last active April 27, 2019 10:14
Show Gist options
  • Save wooseokyourself/c47283a1d9b76c76500a0bf60fafd3db to your computer and use it in GitHub Desktop.
Save wooseokyourself/c47283a1d9b76c76500a0bf60fafd3db to your computer and use it in GitHub Desktop.
나중에 또 저지를 것 같은 프로그래밍 실수 모음
0. 관습적으로 아무 생각 없이 키보드만 두들기지 말고,
내가 적는 라인을 메모리 할당의 측면과, 컴파일&런타임 측면에서 생각하며 코딩하기.
1. 힙에 할당되었던 메모리가 delete로 해제되었다고 하더라도, 포인터는 여전히 해당 메모리주소의 값을 저장하고 있음.
int* k;
k = new int(5);
int* d = k;
cout<<"d's : "<<d<<endl;
cout<<"k's : "<<k<<endl;
delete d;
cout<<"d's : "<<d<<endl;
cout<<"k's : "<<k<<endl;
>> output
d's : 0x7fbb56c02ae0
k's : 0x7fbb56c02ae0
d's : 0x7fbb56c02ae0
k's : 0x7fbb56c02ae0
2. 메모리의 주소 역시 일종의 '값'으로 바라보기.
int* real = new int(5);
int* cpy = real;
int* real = new int(3);
cpy는 real과 동일한 주소값을 저장하고 있었지만, 이후 real은 또 다른 주소값으로 초기화되었다.
그러므로, *cpy = 5 / *real = 3 이다.
즉, 이후 cpy와 real에 대해 모두 delete를 시행해야 한다.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment