skip to Main Content

I add this code to my C++ app but I can’t run the app anymore:

void setclipbord(const char* szBuffer)
{
    OpenClipboard(NULL);

    HGLOBAL hClipboardData = GlobalAlloc(GMEM_MOVEABLE, strlen(szBuffer) + 1);
    char* pchData = (char*)GlobalLock(hClipboardData);
    strcpy(pchData, szBuffer);
    GlobalUnlock(hClipboardData);

    EmptyClipboard();
    SetClipboardData(CF_TEXT, hClipboardData);

    CloseClipboard();
}

I use the last version of Visual Studio 2022, and it reports 1 error and 2 warnings:

Warning ‘hClipboardData’ could be ‘0’, and is a copy of the value found in ‘GlobalAlloc()`169’: this does not adhere to the specification for the function ‘GlobalLock’.

Warning ‘pchData’ could be ‘0’: this does not adhere to the specification for the function ‘strcpy’.

Error ‘strcpy’: This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.

I use these libraries:

#include <iostream>   
#include <string>   
#include <windows.h>   
#include <winuser.h>   
#include <cstring>   
#include <time.h>

2

Answers


  1. It is advised to use strcpy_s() over strcpy() to ensure that you do not edit unallocated memory:

    Copies a string. These versions of strcpy, wcscpy, _mbscpy have security enhancements, as described in Security features in the CRT.

    For the other two warnings, you should always check if the returned value is 0 and return the function if it is so.

    From the GlobalAlloc and GlobalLock documentation:

    If the function fails, the return value is NULL.

    And feel free to just Google it or go to Microsoft documentation website and search for the function and read about it (i. e. remarks, return value and parameters).

    Login or Signup to reply.
  2. You need to define _CRT_SECURE_NO_WARNINGS to use strcpy().

    Just place the following line IN FRONT of your headers (if you place it behind the headers, it wont work):

    #define _CRT_SECURE_NO_WARNINGS
    

    So in the end, your headers should look like this:

    #define _CRT_SECURE_NO_WARNINGS
    #include <iostream>   
    #include <string>   
    #include <windows.h>   
    #include <winuser.h>   
    #include <cstring>   
    #include <time.h>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search