C6001 - initialize memory with new? - c++

Here is my named pipe client sample code for sending a string to a named pipe server using Visual Studio 2019 with ISO C++ 14:
#include <windows.h>
#include <strsafe.h>
void main()
{
DWORD cbRead = 0;
DWORD rv = ERROR_SUCCESS;
WCHAR *sPipename = new WCHAR [1024]();
WCHAR *chReadBuf = new WCHAR [1024]();
WCHAR *sMsgToSend = new WCHAR [1024]();
StringCchCopyW(sPipename, 1024, L"\\\\.\\pipe\\{23E0D6C2-A718-4C91-A81F-4069356686C5}");
StringCchCopy(sMsgToSend, 1024, L"test");
CallNamedPipeW(sPipename, sMsgToSend, (DWORD) (wcslen(sMsgToSend)+1)*sizeof(TCHAR), chReadBuf, 1024*sizeof(TCHAR), &cbRead, 5000);
}
I'm getting C6001 errors on the three variables in the function call, with the compiler showing a warning about not being initialized? They are initialized with parenthesis '( )'.
The suggested fix is to put a {} before the '=' sign. Which gives an error. I googled and searched but could not find an answer to this specific issue.
Thank you, any help is appreciated.

Related

When to use _Notnull_ in C++?

Can someone provide insight when to use _Notnull_? I'm using Visual Studio 2019 and here is my code:
#include <windows.h>
#include <vector>
void WriteIt(_Notnull_ CONST WCHAR* sMsg, _Notnull_ CONST WCHAR* sFileName)
{
FILE* stream;
errno_t err = _wfopen_s(&stream, sFileName, L"a+");
if (err == 0)
if (stream)
{
fwprintf_s(stream, L"%s", sMsg);
fclose(stream);
}
}
int main()
{
WCHAR *sMessage = new WCHAR[16]();
WCHAR *sFile = NULL;
sFile = NULL;
WriteIt(sMessage, sFile);
}
Yet, the _Notnull_ lets the function run. I can't find any documentation on how/why to use it with examples.
Thanks #François Andrieux. Looks like it is used when doing a code analysis from within Visual Studio, where the analyzer can pinpoint if an incoming pointer could be NULL. Here is what the code analyzer says with _Notnull_ is included: Warning C6387 'sFile' could be '0': this does not adhere to the specification for the function 'WriteIt'. Very helpful!

C file cannot be compiled in c++ Visual Studio

For some reason I can no longer compile a c file in my c++ clr console application. It worked before without the clr support, I also switched my project to compile as /TP still not working. Any help would be greatly appreciated.
Error
Severity Code Description Project File Line Suppression State
Error C2664 'int strcmp(const char *,const char *)': cannot convert argument 1 from 'WCHAR [260]' to 'const char *'
snowkill.c
#include "snowkill.h"
void killProcessByName(WCHAR *filename)
{
HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
PROCESSENTRY32 pEntry;
pEntry.dwSize = sizeof(pEntry);
BOOL hRes = Process32First(hSnapShot, &pEntry);
while (hRes)
{
if (strcmp(pEntry.szExeFile, filename) == 0)
{
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0,
(DWORD)pEntry.th32ProcessID);
if (hProcess != NULL && pEntry.th32ProcessID != GetCurrentProcessId())
{
TerminateProcess(hProcess, 9);
CloseHandle(hProcess);
}
}
hRes = Process32Next(hSnapShot, &pEntry);
}
CloseHandle(hSnapShot);
}
snowkill.h
#pragma once
#include "stdafx.h"
#include <windows.h>
#include <process.h>
#include <Tlhelp32.h>
#include <winbase.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
void killProcessByName(WCHAR *filename);
#ifdef __cplusplus
}
#endif
main.cpp
#include "stdafx.h"
#include "snowkill.h"
#include "motion.h"
#include "info.h"
#include "flushsound.h"
#include "snowserial.h"
using namespace System;
bool on() {
return true;
}
bool off() {
return false;
}
int main()
{
listenoncommport();
for (;;) {
string onoff = checkfile();
if (onoff == "1")
{
//detected();
}
else
{
WCHAR *proccc = L"firefox.exe";
killProcessByName(proccc);
//notdetected();
}
Sleep(5000);
}
return 0;
}
You could change every instance of WCHAR to TCHAR so text setting is "generic", or as already mentioned, change the project property character set to be Unicode only.
void killProcessByName(TCHAR *filename)
/* ... */
if (_tcscmp(pEntry.szExeFile, filename) == 0) /* replaced strcmp */
/* ... */
#include <windows.h> /* needed in order to use TEXT() macro */
/* ... */
TCHAR *proccc = TEXT("firefox.exe"); /* TEXT() is a <windows.h> macro */
Use TCHAR type everywhere if the functions involved are not WCHAR specific. That would allow project setting to build either ANSI/ASCII (not set) or Unicode.
Note that Process32First and Process32Next use TCHAR.
This is mostly for legacy, since Windows 2000 and later API functions use Unicode internally, converting ANSI/ASCII to Unicode as needed, while Windows NT and older API functions use ANSI/ASCII.
However, typically many or most text files (such as source code) are ANSI/ASCII and not Unicode, and it's awkward to have to support Unicode for Windows API and then ANSI/ASCII for text files in the same program, and for those projects I use ANSI/ASCII.
By using the TCHAR based generic types, I can share common code with projects that use Unicode and with projects that use ANSI/ASCII.
The error message is clear: you have an error at this precise line:
if (strcmp(pEntry.szExeFile, filename) == 0)
Because your arguments are not of char* type as expected by strcmp but WCHAR* types. You should use wcscmp instead, which is basically the same function, but working with wchar_t* type.
szExeFile in tagPROCESSENTRY32 is declared as TCHAR, which will be a 1-byte char when compiling with Character Set set to 'Not Set' or 'Multibyte'. Set Character Set in your project settings to Use Unicode Character Set to fix the problem.
Also, use wcscmp to compare WCHAR types.

Incompatible with parameter of type "LPCWSTR"

#include "stdafx.h"
#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <dos.h>
using namespace std;
class Dir
{
public:
char* cat;
Dir()
{
cout << "(C:/*)\n";
cat = new char[50];
cin >> cat;
}
void virtual ShowFiles()
{
}
};
class Inside : public Dir
{
public:
void virtual ShowFiles()
{
HANDLE hSearch;
WIN32_FIND_DATA pFileData;
hSearch = FindFirstFile(cat, &pFileData);
if (hSearch != INVALID_HANDLE_VALUE)
do
{
// if ((pFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
cout << pFileData.cFileName << "\n";
} while (FindNextFile(hSearch, &pFileData));
FindClose(hSearch);
}
};
int main()
{
Dir *obj1[2];
obj1[1] = new Inside;
obj1[1]->ShowFiles();
return 0;
}
So I have a program, I need to show with dynamic char cat all file in directory, but it is compilable in Borland C++ but in Visual Studio 15 + Resharper it doesn't work. Severity Code Description Project File Line
Error (active) argument of type "char *" is incompatible with parameter of type "LPCWSTR"
To compile your code in Visual C++ you need to use Multi-Byte char WinAPI functions instead of Wide char ones.
Set Project -> Properties -> Advanced (or. General for older versions) -> Character Set option to Use Multi-Byte Character Set
also see the screenshot
I actually found another way to resolve this error since above method did not work for me.
I casted all my constant character strings with (LPCWSTR). The solution looks like this
Earlier
MessageBox(NULL,"Dialog creation failed! Aborting..", "Error", MB_OK);
After casting to LPCWSTR
MessageBox(NULL, (LPCWSTR) "Dialog creation failed! Aborting..", (LPCWSTR) "Error", MB_OK);
So just copying the (LPCWSTR) and pasting wherever this error was generated resolved all my errors.
Another way to come by this issue, is to use the Lmacro in front of your string.
MessageBox(NULL, L"Dialog creation failed! Aborting..", L"Error", MB_OK);
See: What does the 'L' in front a string mean in C++?
or
L prefix for strings in C++
you can use wchar_t
class Dir
{
public:
wchar_t* cat;
Dir()
{
wcout << "(C:/*)\n";
cat = new wchar_t[50];
wcin >> cat;
}
void virtual ShowFiles()
{
}
};
In Visual Studio 2013 and later, the MFC libraries for multi-byle character encoding (MBCS) will be provided as an add-on to Visual Studio
It will work for any settings:
#include <tchar.h>
MessageBox(NULL, _T("Dialog creation failed! Aborting.."), _T("Error"), MB_OK);

NetUserChangePassword C++

I would like to change user password on my Windows 7 PC using C++.
But when I compile it gets error:
undefined reference to 'NetUserChangePassword'
[Error] ld returned 1 exit status.`
How can I fix it?
Here is the MSDN page with the NetUserChangePassword function:
#ifndef UNICODE
#define UNICODE
#endif
#pragma comment(lib, "netapi32.lib")
#include <iostream>
#include <stdio.h>
#include <windows.h>
#include <lm.h>
bool ChangeUserPassword(LPCWSTR OldPassword, LPCWSTR NewPassword)
{
NET_API_STATUS nStatus;
LPTSTR lp = new TCHAR[256];
DWORD dw = 256;
GetUserName(lp, &dw);
nStatus = NetUserChangePassword(NULL, lp, OldPassword, NewPassword);
delete[] lp;
if (nStatus == NERR_Success)
return true;
return false;
}
int main(int argc, char** argv)
{
LPCWSTR Old_P = L"C";
LPCWSTR New_P = L"D";
ChangeUserPassword(Old_P, New_P);
return 0;
}
I tried to link to the project the winapi32.dll in two ways
i tried to add using the project option
i tried to add following line
HINSTANCE hInst = LoadLibrary( L"C:\\Windows\\System32\\netapi32.dll ");
but i get always the same error
The requirements section of the MSDN topic you linked to states that you must link the Netapi32.lib library. That is the step that you have missed and explains the missing external error.
As to how to resolve the problem it is hard to say for sure. You are not using the MS compiler and so the #pragma approach won't work. Consult the docs for your compiler/linker to work out how to link this library.
It looks like you are using a GCC based compiler and so need to add -lnetapi32 to the options.

Cannot get error code from GetPrivateProfileString

Here is my code.
char BPP[5];
int result, err;
result = GetPrivateProfileStringA("abc", "cba", NULL, BPP, 5, "D:\\aefeaf.ini"); // result = 0
result = _get_errno(&err); // result = 0, err = 0
result = GetLastError(); // result = 0
And description from MSDN: In the event the initialization file specified by lpFileName is not found, or contains invalid values, this function will set errorno with a value of '0x2' (File Not Found). To retrieve extended error information, call GetLastError.
Last parameter is random, the file is not existed. But GetLastError() still return 0. Could someone explain to me why it didn't return 2?
EDIT: As #JochenKalmbach suggest, I ensure my project is not using C++/CLI. And #claptrap said that errorno is a typo (it should be errno), I add _get_errno to my code above. But still, all the error code return is 0. Any help is much appreciated.
Hopefully you are not using C++/CLI... this will mess up the value of "GetLastError" because the code internally uses "IJW" (it just works) and does a bunch of Win32 operations....
FOr native applications, this works as expected:
#include <stdio.h>
#include <tchar.h>
#include <Windows.h>
#include <crtdbg.h>
int _tmain(int argv, char *argc[])
{
char szStr[5];
int result = GetPrivateProfileStringA("abc", "cba", NULL, szStr, 5, "D:\\aefeaf.ini");
_ASSERTE(result == 0);
result = GetLastError();
_ASSERTE(result == 2);
}
If you are using C++/CLI, then you should surround the method with
#pragma managed(push, off)
// Place the method here
#pragma managed(pop);