why CT2A crashes here but works there.


  • #include "stdafx.h"
    #include <atlbase.h>

    void test(char* l, char* r)
     printf("%s \n %s\n", l, r);


    int _tmain(int argc, _TCHAR* argv[])
     TCHAR newfilepath[MAX_PATH] = _T("foo/bar");

     printf("hello %s %s",  "something", CT2A(newfilepath));  // works well
     printf("hello %s %s", CT2A(newfilepath),  "something");  // crash 

     test(  CT2A(newfilepath),  "something" );                // works


    return 0;





    I really cann't explain.

    could somebody straighten me out.

    tku in advance.



    Tuesday, November 04, 2008 3:42 AM

All replies

  • ha,  i just find that the definition of printf use ... ellipsis symb to suppress type check.


    so the temporary object produced by CT2A did NOT apply the LPCSTR translation, so, though printf  expect to receive a char* string, it get a C++ object. That why the 2nd one crashed.


    Nevertheless, i still cannot explain why the first sentence works well ???


    could anybody give me a hand.

    Tuesday, November 04, 2008 3:59 AM
  • Hi,

    I am just wondered if you get an answer for this, then can you share it with that ?

    I am new on MFC programming, and also have this issue.



    Friday, July 01, 2011 5:52 PM
  • As you've discovered, the issue is the ellipsis being a non type-safe operator. You can do any of these and get a working result.

    printf("hello %s %s", CT2A(newfilepath).m_psz,  "something");

    printf("hello %s %s", (LPSTR)CT2A(newfilepath),  "something");

    CT2A ascii(newfilepath);

    printf("hello %s %s", ascii.m_psz,  "something");

    As for why one printf() works and the other doesn't it's probably luck and has to do with the internal implementation of printf.

    Tuesday, July 05, 2011 10:25 PM