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
It is advised to use
strcpy_s()
overstrcpy()
to ensure that you do not edit unallocated memory: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:
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).
You need to define
_CRT_SECURE_NO_WARNINGS
to usestrcpy()
.Just place the following line IN FRONT of your headers (if you place it behind the headers, it wont work):
So in the end, your headers should look like this: