strcpy_s의 두번째 인자에 _TRUNCATE가 들어가면 어떤 현상이 일어날까?

_TRUNCATE의 값은 unsigned int의 최대값 즉 약42억(정확히 42 9496 7295) - 4G - 값이므로 무한대라고 할수 있다.

strcpy_s( a, _TRUNCATE, b) --> strcpy_s( a, 42억, b)..

결론은 strcpy_s를 strcpy로 바꿔버리는 현상(첫번째 인자 버퍼는 보호하지 않음)이 일어난다.
예제 소스
#include <string.h>
#include <iostream>

using namespace std;

int main( int, char *[] )
{
    char    c[16];
    char    a[4];
    
    const char *  b = "012345678901234567890";

    cout << "\n====== memset ======\n";

    memset( a, 'A', sizeof(a) );
    memset( c, 'C', sizeof(c) );

    cout.write( a, _countof(a) ) << endl; // AAAA 출력
    cout.write( c, _countof(c) ) << endl; // CCCCCCCCCCCCCCCC 출력

    /* 예외 발생
    strcpy_s( a, _countof(a), b );
    cout.write( a, _countof(a) ) << endl;
    cout.write( c, _countof(c) ) << endl;
    */ 
    
    cout << "\n====== strcpy_s ======\n";
    strcpy_s( a, _TRUNCATE, b );
    cout.write( a, _countof(a) ) << endl; // 0123 출력
    cout.write( c, _countof(c) ) << endl; // buffer Overflow

    return 0;
}


출력

====== memset ======
AAAA
CCCCCCCCCCCCCCCC

====== strcpy_s ======
0123
234567890    -----> over flow

뱀다리) _TRUNCATE 의 값은 #define _TRUNCATE ((size_t)-1) 이다
그리고 size_t는 unsigned int 형이므로 _TRUNCATE 값은 unsigned int 의 최대값 대략 42억(정확히 42 9496 7295)의 값을 가집니다.

+ Recent posts