invalid cruntime parameter _itoa_s - c++

I have experienced a strange behavior when using _itoa_s and _ultoa_s if I try to get a char array from an DWORD. The function returns zero(success) and my application continues, but I'm getting an exception window with error code 0xc0000417 (STATUS_INVALID_CRUNTIME_PARAMETER).
ULONG pid = ProcessHandleToId(hProcess);
int size = getIntSize(pid);
char *pidStr = new char[size+1];
_ultoa_s(pid, pidStr, size+1, 10);
//do sth with pidStr...
delete[] (pidStr);`
ProcessHandleToId returns the PID (DWORD) for a given ProcessHandle.
getIntSize returns the number of numbers to the corresponding int/char array (5555 => 4).

Yes, the safe CRT functions will abort your program with status code 0xc0000417 when they detect a problem. However, they will do this immediately, the function will not return.
Which means that you are looking at the wrong source code for this problem. It isn't the _ultoa_s() call that's bombing your program. It's another function call, somewhere else in your code. I can't help you find it of course. But the debugger should give you a good idea, look at the call stack when it breaks.

I just compiled your code and it runs fine. The int to string conversion is correct. I assume you bump into security issues due to missing permission when trying to access process handles you don't own.

Related

C++ `if` seems to be taking the wrong branch?

I'm struggling with a non-sensical if statement...
Consider this code in a C++ file
if (coreAudioDevice) {
delete coreAudioDevice;
coreAudioDevice = nullptr;
}
coreAudioDevice = AudioDevice::GetDevice(defaultOutputDeviceID, false, coreAudioDevice, true);
if (coreAudioDevice)
{
coreAudioDevice->setDefaultDevice(true);
// we use the quick mode which skips initialisation; cache the device name (in AudioDevice)
// using an immediate, blocking look-up.
char devName[256];
coreAudioDevice->GetName(devName, 256);
AUDINFO ("Using default output device %p #%d=\"%s\".\n",
defaultOutputDeviceID, coreAudioDevice, coreAudioDevice->GetName());
}
else
AUDERR ("Failed to obtain a handle on the default device (%p)\n", coreAudioDevice);
calling a function in an ObjC++ file:
AudioDevice *AudioDevice::GetDevice(AudioObjectID devId, bool forInput, AudioDevice *dev, bool quick)
{
if (dev) {
if (dev->ID() != devId) {
delete dev;
} else {
return nullptr;
}
}
dev = new AudioDevice(devId, quick, forInput);
return dev;
}
Which leads to the following terminal output:
ERROR coreaudio.cc:232 [init]: Failed to obtain a handle on the default device (0x7f81a1f1f1b0)
Evidently the if shouldn't fail because coreAudioDevice supposedly is NULL and then print a non-null value for this variable in the else branch.
I tried different compiler options and a different compiler (clang 4.0.1 vs. 5.0.1), apparently there is really something fishy in my code. Any thoughts?
Reaching the end of the function without returning a value is undefined behavior in C++.
See http://en.cppreference.com/w/cpp/language/ub and What are all the common undefined behaviours that a C++ programmer should know about?.
So the call setDefaultDevice() can legally result in anything. The compiler is free to compile the program into an executable that can do anything, when the program's control flow leads to undefined behavior (i.e. the call to setDefaultDevice()).
In this case, entering the if block with coreAudioDevice non-zero leads to UB. So the optimizing compiler foresees this and chooses to then make it go into the else branch instead. Like this it can remove the first branch and the if entirely, to produce more optimized code.
See https://blogs.msdn.microsoft.com/oldnewthing/20140627-00/?p=633
Without optimizations the program should normally run as expected.
Well, at least I found a reason, but no understanding (yet).
I had defined this method, without noticing the compiler warning (amidst a bunch of deprecation warnings printed multiple times because of concurrent compilation...):
bool setDefaultDevice(bool isDefault)
{
mDefaultDevice = isDefault;
}
Indeed, no return value.
Notice that I call this method inside the skipped if block - so theoretically I never got the chance to do that. BTW, it's what led me to discover this strange issue.
The issue goes away when I remove the call or when I make the method void as intended.
I think this also explains the very strange way of crashing I've seen: somehow the optimiser gets completely confused because of this. I'm tempted to call this a compiler bug; I don't use the return value from the method, so flow shouldn't be affected at all IMHO.
Ah, right. Should I read that as "free to build an exec that can do anything EXCEPT the sensical thing"? If so, that former boss of mine had a point banning C++ as an anomaly (the exact word was French, "saleté")...
Anyway, I can understand why the behaviour would be undefined when you don't know a function doesn't actually put a return value on the stack. You'd be popping bytes off the stack after the return, messing things up. (Read heap for stack if necessary =] ). I'm guessing that's what would happen when you run this kind of code without optimisation, in good ole C or with the bugggy method defined out of line (so the optimiser cannot know that it's buggy).
But once you know that a function doesn't actually return a value and you see that the value wouldn't be used anyway, you should be able to emit code that doesn't pop the corresponding number of bytes. IOW, code that behaves as expected. With a big fat compile-time warning. Presuming the standard allows this that'd be the sensical thing to do, rather than optimise the entire tainted block away because that'd be faster. If that's indeed the reasoning followed in clang it doesn't actually inspire confidence...
Does the standard say this cannot be an error by default? I'd certainly prefer that over the current behaviour!

A question about the code exception

Env: VS 2008, C++
I have code like below:
void HopeException(LPVOID nVerify)
{
char *p = NULL;
p = (char *)nVerify;
delete []p;
}
When I invoke the function "HopeException" with parameter not-NULL, like:
HopeException(123);
then I hope the program will throw an exception.
But when I compile the code on VS 2008 with Release mode, the program runs well.
I don't know why. Could anyone give me a help about this issue?
Or do you have any good idea to implement the feature with another method?
Edit:
I am so sorry, I think I posted the wrong code before.
Actually, I am doing protection for my software.
My software will get the CRC value of DLL file, and then my software will check the CRC value like below:
unsigned int VerifyCRC = FF234322;
unsinged int CRC = getCRC("Fun.dll");
LPVOID lpResult = CRC & (~VerifyCRC);
HopeException(lpResult);
So according the code below, if the cracker cracks the Fun.dll file, the execute will throw out an exception.
That is really I want.
Jell - C++ gives you enough rope to hang yourself (and most probably most of you friends).
But why do it? (- Suppose it depends on your friends).
You're treating nVerify as an address and assigning it to your pointer p, and then invoking delete[] on that address. If the value of nVerify isn't a valid address you can get undefined behavior, which includes the program appearing to "run well" mostly because you're not really doing much in this function.
What are you really trying to do?
That code shouldn't compile in C++; the closest thing that should compile fine is:
void HopeException(int nVerify)
{
char *p = NULL;
p = (char *)nVerify;
delete []p;
}
This code will crash on VS 2010 Express, so I assume it will also crash in VS 2008. If your goal is to throw a debugger exception directly (on x86) you can just use
__asm int 3;
If your goal is to break into the debugger you can also just use
DebugBreak();

Using 'new' to allocate memory dynamically in C++?

I am working on some C++ code and am having some problems with the function described below. I haven't used much C++ before, at least not for a long time and so i'm trying to learn as I go along to a large extent. The win32api doesn't help much with the confusion factor either...
The function is succesfully called twice, before failing when called at a later stage when it is called in the application.
PTSTR getDomainFromDN(PTSTR dnPtstr) {
size_t nDn=wcslen(dnPtstr);
size_t *pnNumCharConverted = new size_t;
wchar_t *szTemp = new wchar_t[10]; // for debugging purposes
_itow_s((int)nDn,szTemp,10,10); // for debugging purposes
AddToMessageLog(EVENTLOG_ERROR_TYPE,szTemp); // for debugging purposes (displays an integer value before failing)
AddToMessageLog(EVENTLOG_ERROR_TYPE,TEXT("Marker A")); // for debugging purposes
char *dn = new char[nDn];
// !!!!!!!!!!!! all goes wrong here, doesn't get to next line, nDn does have a value when it fails (61)
AddToMessageLog(EVENTLOG_ERROR_TYPE,TEXT("Marker B")); // for debugging purposes
wcstombs_s(pnNumCharConverted,dn,nDn+1,dnPtstr,nDn+1);
...more code here...
delete[] dn;
delete pnNumCharConverted;
return result
}
At first i thought it was a memory allocation problem or something as it fails on the line char *dn = new char[nDn];, the last marker showing as 'Marker A'. I used delete[] on the pointer further down to no avail. I know that nDn is a value because I print this out to a message log using _itow_s for debugging. I also know that dnPtrstr is a PTSTR.
I tried using malloc as well with free() in the old C style but this doesn't improve things.
I tried sanitizing your code a bit. One of the big tricks to C++ is to not explicitly use memory management when it can be avoided. Use vectors instead of raw arrays. Strings instead of char pointers.
And don't unnecessarily allocate objects dynamically. Put them on the stack, where they're automatically freed.
And, as in every other language, initialize your variables.
PTSTR getDomainFromDN(PTSTR dnPtstr) {
std::wstring someUnknownString = dnPtstr;
size_t numCharConverted = 0;
std::wstring temp; // for debugging purposes
std::ostringstream sstr;
sstr << temp;
AddToMessageLog(EVENTLOG_ERROR_TYPE,sstr.str().c_str()); // for debugging purposes (displays an integer value before failing)
AddToMessageLog(EVENTLOG_ERROR_TYPE,TEXT("Marker A")); // for debugging purposes
std::vector<char> dn(someUnknownString.size());
AddToMessageLog(EVENTLOG_ERROR_TYPE,TEXT("Marker B")); // for debugging purposes
wcstombs_s(&numCharConverted, &dn[0], dn.size(), someUnknownString.c_str(), dn.size());
...more code here...
return result
}
This might not have solved your problem, but it has eliminated a large number of potential errors.
Given that I can't reproduce your problem from the code you've supplied, this is really the best I can do.
Now, if you could come up with sane names instead of dnPtstr and dn, it might actually be nearly readable. ;)
i think your problem is this line:
wcstombs_s(pnNumCharConverted,dn,nDn+1,dnPtstr,nDn+1);
because you are telling wcstombs_s to copy up to nDn+1 characters into dn which is only nDn characters long.
try changing the line to:
wcstombs_s(pnNumCharConverted,dn,nDn,dnPtstr,nDn);
or perhaps better yet:
wcstombs_s(pnNumCharConverted,dn,nDn,dnPtstr,_TRUNCATE);
im not sure how you are debugging this or how AddToMessageLog is implemented, but if you are just inspecting the log to trace the code, and AddToMessageLog is buffering your logging, then perhaps the error occurs before that buffer is flushed.
If you are sure that "char *dn = new char[nDn];" is failing, TRY "set_new_handler" -> http://msdn.microsoft.com/en-us/library/5fath9te(VS.80).aspx
On a side note, few things:
The very first operation "size_t nDn=wcslen(dnPtstr);" is not 100% correct. You are doing wcslen on dnPtstr assuming dnPtstr to be unicode. However, this is not the case since it could be PWSTR or PSTR based on whether UNICODE is defined or not. So, use _tcslen(). Its better if you give some time to understand UNICODE, NON-UNICODE stuff since they would help you a lot in Windows C++ development.
Why are you using so many "new" if you are using these variables only in this function (I am assuming it). Prefer stack over heap for local variables unles you have a definite requirement.

C++ Runtime Error caused by adding new function (which isn't ever used beyond it's definition)

This has been stumping me for a bit. I have a Class written in C++.
Everything works fine.
Next, I add function void A(); to the header file and run, It still works fine.
However as soon as I add a new function definition to the CPP file, I get a runtime error every single time. (specifically: Process terminated with status -1073741510 (0 minutes, 7 seconds)
void ClassName::A() {
}
I am running using Code::Blocks on Windows, also strange but the permissions of the output directory are all changed after the crash and the folders/files are all set to Read Only.
Note: there are NO references/uses of the function elsewhere in the code, only the definition. I am interested in what sort of bug could cause this kind of runtime error? Possibly a memory leak somewhere?
Usually such an error is the result of memory corruption somewhere in the program.
Sounds like you have a wild pointer somewhere.

Remove never-run call to templated function, get allocation error on run-time

I have a piece of templated code that is never run, but is compiled. When I remove it, another part of my program breaks.
First off, I'm a bit at a loss as to how to ask this question. So I'm going to try throwing lots of information at the problem.
Ok, so, I went to completely redesign my test project for my experimental core library thingy. I use a lot of template shenanigans in the library. When I removed the "user" code, the tests gave me a memory allocation error. After quite a bit of experimenting, I narrowed it down to this bit of code (out of a couple hundred lines):
void VOODOO(components::switchBoard &board) {
board.addComponent<using_allegro::keyInputs<'w'> >();
}
Fundementally, what's weirding me out is that it appears that the act of compiling this function (and the template function it then uses, and the template functions those then use...), makes this bug not appear. This code is not being run. Similar code (the same, but for different key vals) occurs elsewhere, but is within Boost TDD code.
I realize I certainly haven't given enough information for you to solve it for me; I tried, but it more-or-less spirals into most of the code base. I think I'm most looking for "here's what the problem could be", "here's where to look", etc. There's something that's happening during compile because of this line, but I don't know enough about that step to begin looking.
Sooo, how can a (presumably) compilied, but never actually run, bit of templated code, when removed, cause another part of code to fail?
Error:
Unhandled exceptionat 0x6fe731ea (msvcr90d.dll) in Switchboard.exe:
0xC0000005: Access violation reading location 0xcdcdcdc1.
Callstack:
operator delete(void * pUser Data)
allocator< class name related to key inputs callbacks >::deallocate
vector< same class >::_Insert_n(...)
vector< " " >::insert(...)
vector<" ">::push_back(...)
It looks like maybe the vector isn't valid, because _MyFirst and similar data members are showing values of 0xcdcdcdcd in the debugger. But the vector is a member variable...
Update: The vector isn't valid because it's never made. I'm getting a channel ID value stomp, which is making me treat one type of channel as another.
Update:
Searching through with the debugger again, it appears that my method for giving each "channel" it's own, unique ID isn't giving me a unique ID:
inline static const char channel<template args>::idFunction() {
return reinterpret_cast<char>(&channel<CHANNEL_IDENTIFY>::idFunction);
};
Update2: These two are giving the same:
slaveChannel<switchboard, ALLEGRO_BITMAP*, entityInfo<ALLEGRO_BITMAP*>
slaveChannel<key<c>, char, push<char>
Sooo, having another compiled channel type changing things makes sense, because it shifts around the values of the idFunctions? But why are there two idFunctions with the same value?
you seem to be returning address of the function as a character? that looks weird. char has much smaller bit count than pointer, so it's highly possible you get same values. that could reason why changing code layout fixes/breaks your program
As a general answer (though aaa's comment alludes to this): When something like this affects whether a bug occurs, it's either because (a) you're wrong and it is being run, or (b) the way that the inclusion of that code happens to affect your code, data, and memory layout in the compiled program causes a heisenbug to change from visible to hidden.
The latter generally occurs when something involves undefined behavior. Sometimes a bogus pointer value will cause you to stomp on a bit of your code (which might or might not be important depending on the code layout), or sometimes a bogus write will stomp on a value in your data stack that might or might not be a pointer that's used later, or so forth.
As a simple example, supposing you have a stack that looks like:
float data[10];
int never_used;
int *important pointer;
And then you erroneously write
data[10] = 0;
Then, assuming that stack got allocated in linear order, you'll stomp on never_used, and the bug will be harmless. However, if you remove never_used (or change something so the compiler knows it can remove it for you -- maybe you remove a never-called function call that would use it), then it will stomp on important_pointer instead, and you'll now get a segfault when you dereference it.