cpp 질문

익명 사용자의 이미지

#include <string>
#include <iostream>
std::string str_func(){
        std::string a = "aaaa";
        return a;
}
void display_string(const char * buf){
        std::cout << buf << std::endl;
}
int main(void) {
    const char *str = str_func().c_str();
    display_string(str);
    std::string b = "bbbb"; //uaf
    display_string(str);  /* Undefined behavior */
}

여기서 2번째 display_string(str)에 왜 aaaa가 출력되는지 모르겠습니다.

지나가던초보의 이미지

https://en.wikipedia.org/wiki/Undefined_behavior

읽어보시길 추천드려요.

지나가던초보의 이미지

const auto str = str_func().c_str();

이것과

const auto s = str_func();
const auto str = s.c_str();

둘의 차이는 무엇일까요?

익명 사용자의 이미지

이거 안 될 거라는 생각은 쉽게 할 수 있는데
(c_str이 가리키는 string 내부 데이터는 임시 string 객체가 소멸하면서 해제되겠죠)

왜 안 되는지 이유를 찾기가 쉽지 않네요.

물론 메모리가 할당 해제된다고 데이터가 즉시 사라지는 건 아니니까 출력은 될 수 있겠지만

그렇다고 이런 식으로 코드 짜도 되는 건 아닐 텐데, 금지하는 규칙을 찾기 어려워서 답변이 궁색하군요.

좀 더 찾아 봐야겠습니다. -_-;;

지나가던초보의 이미지

왜 안 되는지에 대한 이유는 간단합니다.
댕글링 포인터에 대한 억세스는 미정의 동작이기 때문입니다.

https://en.wikipedia.org/wiki/Dangling_pointer

> Object backing the pointer will be destroyed at the end of the full-expression

https://stackoverflow.com/questions/64657316/warning-object-backing-the-pointer-will-be-destroyed-at-the-end-of-the-full-exp

https://releases.llvm.org/10.0.0/tools/clang/docs/DiagnosticsReference.html#wdangling-gsl