인프런 커뮤니티 질문&답변
c style 문자열에대해
작성
·
293
1
안녕하세요
음 .. 어찌보면 c강의에 질문드려야 할 것 같기도한데 공통적인? 내용이니 여기다가 질문드립니다!
제가 알기로는
const char* String="hello" ; 의 "hello" 같은 문자열 리터럴은 끝에 '₩0'을 하나붙여 메모리의 ' 데이터 영역(BSS)ㅡ읽기만 가능한 영역' 에 저장되어 프로그램 종료시까지 존재하는것으로 알고있습니다.(그래서 같은 내용의 문자열 호출시 같은 문자열을 반복사용하는것으로 알고있구요)
그런데 cout<<"hello"; cout<<"good bye" ;
string my_str="nice" char str[]="good "
의 "hello" , "good bye" "nice" "good"처럼 한번쓰고 사라질 문자열도 위와 마찬가지로 끝에 '₩0'을 하나붙여 bss - 읽기만 가능한 영역 에 저장되어 종료시까지 살아있나요?
감사합니다
답변 4
1
1
C 강의는 제가 필요한 경우 부분적으로만 들어서 그 부분을 놓쳤었군요. 감사합니다.
상황상 어려울 수도 있겠구나... 생각하여 조금 더 달아드리겠습니다. 첫번째는 C++ code이고, 두번째 코드는 Dubug mode에서 disassembler를 이용하여 얻은 x86 architecture assembly code입니다. 보셔야할 부분은
push offset string "Hello" (0269B30h) 으로 주소를 보면 모두 같은 것을 확인할 수 있습니다.
대강 구조를 상상하실 수 있을거라 생각합니다.
#include <iostream>
using namespace std;
int main() {
cout << "Hello" << endl;
cout << "Hello" << endl;
const char str[] = "Hello";
}
cout << "Hello" << endl;
00262422 push offset string "Hello" (0269B30h)
00262427 mov eax,dword ptr [_imp_?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A (026D0D4h)]
0026242C push eax
0026242D call std::operator<<<std::char_traits<char> > (02614F6h)
00262432 add esp,8
00262435 mov dword ptr [ebp-0D8h],eax
0026243B mov esi,esp
0026243D push offset std::endl<char,std::char_traits<char> > (0261307h)
00262442 mov ecx,dword ptr [ebp-0D8h]
00262448 call dword ptr [__imp_std::basic_ostream<char,std::char_traits<char> >::operator<< (026D0A0h)]
0026244E cmp esi,esp
00262450 call __RTC_CheckEsp (02612DFh)
cout << "Hello" << endl;
00262455 push offset string "Hello" (0269B30h)
0026245A mov eax,dword ptr [_imp_?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A (026D0D4h)]
0026245F push eax
00262460 call std::operator<<<std::char_traits<char> > (02614F6h)
00262465 add esp,8
00262468 mov dword ptr [ebp-0D8h],eax
0026246E mov esi,esp
00262470 push offset std::endl<char,std::char_traits<char> > (0261307h)
00262475 mov ecx,dword ptr [ebp-0D8h]
0026247B call dword ptr [__imp_std::basic_ostream<char,std::char_traits<char> >::operator<< (026D0A0h)]
00262481 cmp esi,esp
00262483 call __RTC_CheckEsp (02612DFh)
const char str[] = "Hello";
00262488 mov eax,dword ptr [string "Hello" (0269B30h)]
0026248D mov dword ptr [str],eax
00262490 mov cx,word ptr ds:[269B34h]
00262497 mov word ptr [ebp-0Ch],cx
}
1
후자의 경우에 제가 BSS Segment라 하였는데 , 죄송합니다 ! 실수했습니다 .
따배C 11.2강 10분50초 경을 보시면 아실 수 있습니다. BSS Segment가 아닌, Data Segment 의 Read only Segment입니다.
전자의 경우 , 으음... 확실히 확인하기는 어려운 문제같네요 . 답변 감사합니다!!!
1
hello , good bye... 이런 식으로 출력하려면 컴퓨터는 메모리상의 어딘가에 저장을 해야합니다. 읽기만 가능한 영역에 저장되는 것은 맞다고 생각합니다.
https://stackoverflow.com/questions/51592/is-there-a-need-to-destroy-char-string-or-char-new-char6/51607#51607
이 글을 읽어보시는 것이 도움이 될 수 있을 것 같고,
bss segment에 대해서는 저도 잘 몰랐던 부분이라 아래의 두 글을 읽어보니 생각하시는 것과는 조금 다른 것 같은데, 어디서 그런 내용을 볼 수 있나요?
https://en.wikipedia.org/wiki/Data_segment
https://en.wikipedia.org/wiki/.bss





