Info

문자열 리터럴값의 경우 읽기 전용(read-only) 전역 정적 공간에 저장되며(.rodata), 동일한 리터럴의 경우에는 동일한 주소를 가지도록 최적화된다. 이것을 string pooling이라고 한다.

해당 글에서는 이에 대한 예제를 살펴보고 마무리한다.

바로 예제를 살펴보자.

__attribute__((noinline)) // Prevent inlining
int test(long long choice) {
	volatile int ret = choice;
 
	const char* a = "ON";
//	const char* b = "ON";
 
	volatile long long a_addr = a;
//	volatile long long b_addr = b;
 
    // Compare the two pointers:
    if (a_addr == choice) {
        ret = 0;
    } else {
        ret = 10;
    }
 
	return ret;
}
 
/**
 * @brief  main function used for debug purpose
  * @retval the function always returns 0
 */
int main(void)
{
	const char* b = "ON";
	volatile long long a = b;
	test(a);
 
    while (1);
 
    return 0;
}

예제에서 다른 함수, 같은 함수에 대해서 모두 비교해봤을 때, ret = 0을 통해서 문자열 리터럴은 같은 주소를 가지는 것을 확인했다.