String copy

This is a discussion on String copy within the C++ Programming forums, part of the General Programming Boards category; I would like to copy the string returned in FormatMessage() in the error array, but i only get garbage. I ...

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

    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;
    }
    Compiler MSVC++ 2013 with Code::Blocks.

  2. #2
    a_capitalist_story
    Join Date
    Dec 2007
    Posts
    2,650
    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
    796
    Yes, you're right, thanks rags_to_riches.

    Anyway I just went with the easier solution and declared it globally to solve the problem.
    Compiler MSVC++ 2013 with Code::Blocks.

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

  5. #5
    Registered User
    Join Date
    Dec 2007
    Posts
    796
    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.
    Compiler MSVC++ 2013 with Code::Blocks.

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, 11:18 AM
  3. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 04:45 PM
  4. Replies: 4
    Last Post: 03-03-2006, 01:11 AM
  5. Replies: 3
    Last Post: 11-03-2002, 01:14 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21