Thread: String copy

  1. #1
    Registered User
    Join Date
    Dec 2007
    Posts
    932

    String copy

    I would like to copy the string returned in FormatMessage() in the error array, but i only get garbage.
    I dont know if the problem comes from the fact that FormatMessage() takes a tchar as a 5th parameter.


    Code:
    char * reportError()
    {
        LPVOID Buf;
    
        FormatMessage(
            FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
            NULL,
            GetLastError(),
            MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), 
            (LPTSTR) &Buf,
            0,
            NULL );
    
        cout << (char*)Buf << "\n";
        char error[260] ="";
        strcpy(error, (char*) Buf);
    
        LocalFree( Buf );
        return error;
    }
    Using Windows 10 with Code Blocks and MingW.

  2. #2
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    You're returning a local variable that goes out of scope when you leave the function. You need to dynamically allocate the memory into which you're copying the string.

  3. #3
    Registered User
    Join Date
    Dec 2007
    Posts
    932
    Yes, you're right, thanks rags_to_riches.

    Anyway I just went with the easier solution and declared it globally to solve the problem.
    Using Windows 10 with Code Blocks and MingW.

  4. #4
    Registered User
    Join Date
    Dec 2007
    Posts
    2,675
    Not the right solution, but whatever. Globals are very, VERY rarely the right solution.

  5. #5
    Registered User
    Join Date
    Dec 2007
    Posts
    932
    Thanks ill consider then to go the other way.

    So i think in that case i could just return 'Buf', directly without assigning it, and then use LocalFree( Buf2 ); after i called the function , right?

    Code:
    Buf2 =  reportError();
    LocalFree( Buf2 );
    Last edited by Ducky; 08-24-2010 at 07:15 AM.
    Using Windows 10 with Code Blocks and MingW.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Polymorphism and generic lists
    By Shibby3 in forum C# Programming
    Replies: 9
    Last Post: 07-26-2010, 05:27 AM
  2. Help for my assigment
    By cloverdagreat in forum C Programming
    Replies: 16
    Last Post: 11-21-2009, 12:18 PM
  3. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  4. Replies: 4
    Last Post: 03-03-2006, 02:11 AM
  5. Replies: 3
    Last Post: 11-03-2002, 02:14 AM