lstrcpy() causing exceptions in visual C++ code - exception

I used a MFC virtual list control to enhance the performance and I handle GetDispInfo(NMHDR* pNMHDR, LRESULT* pResult) to populate the ListCtrl. The relevant code in that method is as follows:
if (pItem->mask && LVIF_TEXT)
{
switch(pItem->iSubItem)
{
case 0:
lstrcpy(pItem->pszText, rLabel.m_strText);
break;
case 1:
sprintf(pItem->pszText, "%d", p.o_Value);
break;
default:
ASSERT(0);
break;
}
}
Here, when I use lstrcpy(),when I'm srolling down/up, I get a whole lot of exceptions saying First-chance exception at 0x7c80c741 in test_list_control.exe: 0xC0000005: Access violation writing location 0xb70bf2ac. These messages appear in the debug output. But the program doesn't crash. Can anyone please explain what the matter here and how should I overcome that??
rLabel is a CLabelItem which I have declared earlier.
Thank you!

If all you see is the first chance exception thing, stop worrying. See for example Link but you can find similar pages all over the place (mostly from 5-10 years ago.) It means some code threw and the exception was caught and dealt with. I see this in MFC apps some times. As the blog entry says
First chance exception messages most
often do not mean there is a problem
in the code.
I would wait until you see actual errors before getting worked up about this one.

I think you should check if buffer that is pointed by pItem->pszText is large enough to hold rLabel.m_strText. Or if rLabel.m_strText is correct null terminated string. For me this looks like writing uninitialized memory. Use the debugger to check this.

Related

Uncaught (in promise) -- How to find the source of the problem in a Deno program

I'm having trouble with my Deno program. I'm getting messages like this:
error: Uncaught (in promise) Error: No such host is known. (os error 11001)
at deno:core/01_core.js:106:46
at unwrapOpResult (deno:core/01_core.js:126:13)
at async Object.connect (deno:extensions/net/01_net.js:219:13)
Then deno exits.
I don't know how to debug this. This stack trace only points to code that comes with Deno, not to my code.
I've searched my code and I've put a .catch() or a try/catch everywhere I can think of, but that did not help.
Is there anything I can do to help me find the problem? I'd love it if I could get a complete stack dump. Or if I could have the debugger pause at the problem. Or if you have any other suggestions.
Thanks!
Edit 8/29/2021
I found two bugs in my code. Here are the actual bugs. It was a serious pain to track these down. I'm still looking for a tool or process to help the next time I make a silly mistake like this.
Bug #1:
I was using try/catch (shown in red) when I should have been using .catch() (shown in green). My try/catch did nothing. If there was an error sending the data, that would cause my program to crash.
Bug #2:
const promise = Deno.connect(options);
promise.catch(reportError);
promise.then(longRunningTask);
await someOtherPromise;
promise.then(connection => {
// We never get to here.
try {
connection.close();
} catch {
console.log("🙁");
}
});
// And we never get to here.
The code I've shown here was spread throughout a much longer program. I did not understand the rules regarding promises. The second .then() requires a second .catch().
Here was one of my attempts to solve this problem. I told VS code to break on all exceptions. It seems to ignore my request. I never got to a breakpoint, but the debug console shows that the program crashed because of an exception.

Restkit: getting objc_exception_throw in saveContextToPersistentStore, RKManagedObjectRequestOperation.m

I am getting, just for once every app runtime, an exception in the method saveContextToPersistentStore in RKManagedObjectRequestOperation.m: on line
success = [contextToSave save:&localError];
success is YES, localError is nil. I can continue the program execution in debugger.
I tried to wrap it with #try block but with no success (as something else took care of this) to get more information why it happens.
Can you help me to investigate the cause of this? Is this something I should pay attention to? This answer may targets this issues. But I am not sure, if the problem is local or caused in higher layers (Restkit mapping).
Stack:

How to debug a runtime stack underflow error?

I'm really struggling to resolve a stack underflow that I'm getting. The traceback I get at runtime is:
VerifyError: Error #1024: Stack underflow occurred.
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()
This is particularly difficult to debug because when I run in debug mode it does not happen at all. It only happens when compiled as a release.
Does anyone have any tips on how to debug a Stack Underflow? Are have a clean explanation of what that means for Flash?
In case it helps, this error is occurring when I click a button whose handler makes an RPC call, which uses a URLLoader, an AsyncToken, and then invokes the set of AsyncResponder instances associated with the AsyncToken. With some server-side logging as well as some logging hacked into the swf, I know that the UrlLoader is successfully doing and GET'ing a crossdomain.xml file, is correctly processing it (ie: if I wreck it, I get a security error), and is also successfully completing the "load" request (the server sends the data). The underflow seems to be happening in the Event.COMPLETE listening/handling process (as is, of course, implied by the traceback as well).
mxmlc used = from flex_sdk_4.5.0.20967
Example player (I've tried a few) = 10.2.153.1
UPDATE: My specific problem is solved... but I'm leaving the question as-is since I would like to know how to generally debug such a problem, rather than just getting my specific solution.
In my code I had the following Application definition:
<s:Application height="100%" width="100%"
xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
initialize="InitData();">
Note that the code is/was attached to the initialize event.
InitData() and relevant defintions are/were:
import classes.RpcServerProxy;
public var SP:RpcServerProxy;
public function InitData():void {
SP = new RpcServerProxy("http://192.168.1.102:1234");
}
When I switched the InitData() call to be on the onCompletion event instead of initialize (thanks J_A_X!), the problem goes away entirely. What seems to have been happening was that the Event.COMPLETE event handler (onComplete in the stack trace) was using the global SP object. Something about the release (vs debug) compilation must have been affecting the startup timing of the SP variable initialization. Moving the handler later to the onCompletion event resolved all issues.
As said above, I would still like to know what tricks/tools are available for debugging initialization issues like this.
UPDATE 2:
applicationComplete seems to be an even better event than creationComplete to put application initialization code. See this blog entry for some explanation, and and this video (around 4:25) by an Adobe Tech Evangelist for an example of simple "start of application" data initialization.
I got rid of this error by adding compiler argument:
-omit-trace-statements=false
Stack underflow basically means the compiler messed up.
You can use SWFWire Inspector to look at the bytecode of the event handler, if you want to know exactly how it messed up. You can also use SWFWire Debugger to see which methods were called, but in this case, you already knew where it was happening.
If you post the broken swf, I can give you more info.
Sean is right that to debug it you can look at the byte code, but that didn't sound appealing to me.
Based on my experience and research, it is often due to the presence of a trace statement that incorrectly gets compiled out in release mode, and generates invalid byte code. So, I would say to "debug" it, "Look for places where you are using trace. Try commenting them all out in the offending function and see if the issue goes away."
In my case, it was a trace statement as the first line of a catch block:
catch (e:TypeError) {
trace(e.getStackTrace()); //This line is the problem
throw new Error("Unexpected type encountered");
}
I found someone else with this exact issue here.
This code also leads to stack underflow only in release mode (flag -debug=false):
true && trace('123');
mxlmc flex sdk version 4.5.0.20967, flashplayer version 10.3.181.14 (linux).
Check your code for similar expressions.
This code caused me issues when I compiled a release candidate from flash builder 4.5
public function set configVO( value:PopupConfigVO ):void
{trace("CHANGING")
Resolved by inserting a space between the the trace and curly brace
public function set configVO( value:PopupConfigVO ):void
{ trace("CHANGING")
Hope this helps.
For people looking for the same problem, I just got this caused by a trace statement in the 'default' case of a switch statement. Commented out the trace, stack underflow resolved.
Interesting... I was getting this error with a SWF that I'd pulled off the web, an Away3D based graphics demo. At the time I was running this on the Tamarin VM rather than the actual Flash/AIR runtimes, so could stick a breakpoint on the "verifyFailed(kStackUnderflowError)" line and see what was happening.
The -Dverbose flag also helped find the culprit:
typecheck MethodInfo-1480()
outer-scope = [global]
[Object~ Object] {} ()
0:pop
VERIFY FAILED: Error #1024: Stack underflow occurred.
And looking at the ABC using SWFInvestigator, I found this:
var function(Object):void /* disp_id=0 method_id=1480 nameIndex = 0 */
{
// local_count=2 max_scope=0 max_stack=0 code_len=2
// method position=52968 code position=155063
0 pop
1 returnvoid
}
So there is an obvious issue where the 'trace' has been removed but the compiler has put a 'pop' in there: I wouldn't have thought this was needed as a trace call should presumably have been made via 'callpropvoid'?
Quite why this doesn't fail on AIR/Flash I don't know..
Anyway: looks to me like an ASC compiler problem i.e perhaps one of the ActionScript3 compilers had a fault with this - hence the workarounds that have been mentioned so far.
It's quite simple, and it doesn't have anything to do with spaces before or after brackets, trace commands or whatever else: it's just 1 really simple thingy:
DO NOT LOOP EMPTY!
Meaning, while developing, we all //comment some lines sometimes, and when that results in
for (...) {
// skip for now
}
the compiler gets :
for(...){}
and that my good friends, is something the compiler doesn't like!
so, NO empty loops, and you're on your way again...
Happy hunting,
P.
I had the exact same problem, but in my case the cause of the problem was a trace statement in a place where the compiler didn't expect it to find it, right after a package declaration at the beginning of the class:
package utils
{
trace ("trace something here");
And that's why compiling in debug mode removed the problem.

Why are empty catch blocks a bad idea? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I've just seen a question on try-catch, which people (including Jon Skeet) say empty catch blocks are a really bad idea? Why this? Is there no situation where an empty catch is not a wrong design decision?
I mean, for instance, sometimes you want to get some additional info from somewhere (webservice, database) and you really don't care if you'll get this info or not. So you try to get it, and if anything happens, that's ok, I'll just add a "catch (Exception ignored) {}" and that's all
Usually empty try-catch is a bad idea because you are silently swallowing an error condition and then continuing execution. Occasionally this may be the right thing to do, but often it's a sign that a developer saw an exception, didn't know what to do about it, and so used an empty catch to silence the problem.
It's the programming equivalent of putting black tape over an engine warning light.
I believe that how you deal with exceptions depends on what layer of the software you are working in: Exceptions in the Rainforest.
They're a bad idea in general because it's a truly rare condition where a failure (exceptional condition, more generically) is properly met with NO response whatsoever. On top of that, empty catch blocks are a common tool used by people who use the exception engine for error checking that they should be doing preemptively.
To say that it's always bad is untrue...that's true of very little. There can be circumstances where either you don't care that there was an error or that the presence of the error somehow indicates that you can't do anything about it anyway (for example, when writing a previous error to a text log file and you get an IOException, meaning that you couldn't write out the new error anyway).
I wouldn't stretch things as far as to say that who uses empty catch blocks is a bad programmer and doesn't know what he is doing...
I use empty catch blocks if necessary. Sometimes programmer of library I'm consuming doesn't know what he is doing and throws exceptions even in situations when nobody needs it.
For example, consider some http server library, I couldn't care less if server throws exception because client has disconnected and index.html couldn't be sent.
Exceptions should only be thrown if there is truly an exception - something happening beyond the norm. An empty catch block basically says "something bad is happening, but I just don't care". This is a bad idea.
If you don't want to handle the exception, let it propagate upwards until it reaches some code that can handle it. If nothing can handle the exception, it should take the application down.
I think it's okay if you catch a particular exception type of which you know it's only going to be raised for one particular reason, and you expect that exception and really don't need to do anything about it.
But even in that case, a debug message might be in order.
There are rare instances where it can be justified. In Python you often see this kind of construction:
try:
result = foo()
except ValueError:
result = None
So it might be OK (depending on your application) to do:
result = bar()
if result == None:
try:
result = foo()
except ValueError:
pass # Python pass is equivalent to { } in curly-brace languages
# Now result == None if bar() returned None *and* foo() failed
In a recent .NET project, I had to write code to enumerate plugin DLLs to find classes that implement a certain interface. The relevant bit of code (in VB.NET, sorry) is:
For Each dllFile As String In dllFiles
Try
' Try to load the DLL as a .NET Assembly
Dim dll As Assembly = Assembly.LoadFile(dllFile)
' Loop through the classes in the DLL
For Each cls As Type In dll.GetExportedTypes()
' Does this class implement the interface?
If interfaceType.IsAssignableFrom(cls) Then
' ... more code here ...
End If
Next
Catch ex As Exception
' Unable to load the Assembly or enumerate types -- just ignore
End Try
Next
Although even in this case, I'd admit that logging the failure somewhere would probably be an improvement.
Per Josh Bloch - Item 65: Don't ignore Exceptions of Effective Java:
An empty catch block defeats the purpose of exceptions
At the very least, the catch block should contain a comment explaining why it is appropriate to ignore the exception.
Empty catch blocks are usually put in because the coder doesn't really know what they are doing. At my organization, an empty catch block must include a comment as to why doing nothing with the exception is a good idea.
On a related note, most people don't know that a try{} block can be followed with either a catch{} or a finally{}, only one is required.
An empty catch block is essentially saying "I don't want to know what errors are thrown, I'm just going to ignore them."
It's similar to VB6's On Error Resume Next, except that anything in the try block after the exception is thrown will be skipped.
Which doesn't help when something then breaks.
This goes hand-in-hand with, "Don't use exceptions to control program flow.", and, "Only use exceptions for exceptional circumstances." If these are done, then exceptions should only be occurring when there's a problem. And if there's a problem, you don't want to fail silently. In the rare anomalies where it's not necessary to handle the problem you should at least log the exception, just in case the anomaly becomes no longer an anomaly. The only thing worse than failing is failing silently.
Empty catch blocks are an indication of a programmer not knowing what to do with an exception. They are suppressing the exception from possibly bubbling up and being handled correctly by another try block. Always try and do something with the exception you are catching.
I think a completely empty catch block is a bad idea because there is no way to infer that ignoring the exception was the intended behavior of the code. It is not necessarily bad to swallow an exception and return false or null or some other value in some cases. The .net framework has many "try" methods that behave this way. As a rule of thumb if you swallow an exception, add a comment and a log statement if the application supports logging.
If you dont know what to do in catch block, you can just log this exception, but dont leave it blank.
try
{
string a = "125";
int b = int.Parse(a);
}
catch (Exception ex)
{
Log.LogError(ex);
}
Because if an exception is thrown you won't ever see it - failing silently is the worst possible option - you'll get erroneous behavior and no idea to look where it's happening. At least put a log message there! Even if it's something that 'can never happen'!
I find the most annoying with empty catch statements is when some other programmer did it. What I mean is when you need to debug code from somebody else any empty catch statements makes such an undertaking more difficult then it need to be. IMHO catch statements should always show some kind of error message - even if the error is not handled it should at least detect it (alt. on only in debug mode)
It's probably never the right thing because you're silently passing every possible exception. If there's a specific exception you're expecting, then you should test for it, rethrow if it's not your exception.
try
{
// Do some processing.
}
catch (FileNotFound fnf)
{
HandleFileNotFound(fnf);
}
catch (Exception e)
{
if (!IsGenericButExpected(e))
throw;
}
public bool IsGenericButExpected(Exception exception)
{
var expected = false;
if (exception.Message == "some expected message")
{
// Handle gracefully ... ie. log or something.
expected = true;
}
return expected;
}
Generally, you should only catch the exceptions you can actually handle. That means be as specific as possible when catching exceptions. Catching all exceptions is rarely a good idea and ignoring all exceptions is almost always a very bad idea.
I can only think of a few instances where an empty catch block has some meaningful purpose. If whatever specific exception, you are catching is "handled" by just reattempting the action there would be no need to do anything in the catch block. However, it would still be a good idea to log the fact that the exception occurred.
Another example: CLR 2.0 changed the way unhandled exceptions on the finalizer thread are treated. Prior to 2.0 the process was allowed to survive this scenario. In the current CLR the process is terminated in case of an unhandled exception on the finalizer thread.
Keep in mind that you should only implement a finalizer if you really need one and even then you should do a little as possible in the finalizer. But if whatever work your finalizer must do could throw an exception, you need to pick between the lesser of two evils. Do you want to shut down the application due to the unhandled exception? Or do you want to proceed in a more or less undefined state? At least in theory the latter may be the lesser of two evils in some cases. In those case the empty catch block would prevent the process from being terminated.
I mean, for instance, sometimes you want to get some additional info from somewhere (webservice, database) and you really don't care if you'll get this info or not. So you try to get it, and if anything happens, that's ok, I'll just add a "catch (Exception ignored) {}" and that's all
So, going with your example, it's a bad idea in that case because you're catching and ignoring all exceptions. If you were catching only EInfoFromIrrelevantSourceNotAvailable and ignoring it, that would be fine, but you're not. You're also ignoring ENetworkIsDown, which may or may not be important. You're ignoring ENetworkCardHasMelted and EFPUHasDecidedThatOnePlusOneIsSeventeen, which are almost certainly important.
An empty catch block is not an issue if it's set up to only catch (and ignore) exceptions of certain types which you know to be unimportant. The situations in which it's a good idea to suppress and silently ignore all exceptions, without stopping to examine them first to see whether they're expected/normal/irrelevant or not, are exceedingly rare.
There are situations where you might use them, but they should be very infrequent. Situations where I might use one include:
exception logging; depending on context you might want an unhandled exception or message posted instead.
looping technical situations, like rendering or sound processing or a listbox callback, where the behaviour itself will demonstrate the problem, throwing an exception will just get in the way, and logging the exception will probably just result in 1000's of "failed to XXX" messages.
programs that cannot fail, although they should still at least be logging something.
for most winforms applications, I have found that it suffices to have a single try statement for every user input. I use the following methods: (AlertBox is just a quick MessageBox.Show wrapper)
public static bool TryAction(Action pAction)
{
try { pAction(); return true; }
catch (Exception exception)
{
LogException(exception);
return false;
}
}
public static bool TryActionQuietly(Action pAction)
{
try { pAction(); return true; }
catch(Exception exception)
{
LogExceptionQuietly(exception);
return false;
}
}
public static void LogException(Exception pException)
{
try
{
AlertBox(pException, true);
LogExceptionQuietly(pException);
}
catch { }
}
public static void LogExceptionQuietly(Exception pException)
{
try { Debug.WriteLine("Exception: {0}", pException.Message); } catch { }
}
Then every event handler can do something like:
private void mCloseToolStripMenuItem_Click(object pSender, EventArgs pEventArgs)
{
EditorDefines.TryAction(Dispose);
}
or
private void MainForm_Paint(object pSender, PaintEventArgs pEventArgs)
{
EditorDefines.TryActionQuietly(() => Render(pEventArgs));
}
Theoretically, you could have TryActionSilently, which might be better for rendering calls so that an exception doesn't generate an endless amount of messages.
You should never have an empty catch block. It is like hiding a mistake you know about. At the very least you should write out an exception to a log file to review later if you are pressed for time.

How to trace COM objects exceptions?

I have a DLL with some COM objects. Sometimes, this objects crashes and register an error event in the Windows Event Log with lots of hexadecimal informations. I have no clue why this crashes happens.
So, How can I trace those COM objects exceptions?
The first step is to lookup the Fail code's hex value (E.G. E_FAIL 0x80004005). I've had really good luck with posting that value in Google to get a sense of what the error code means.
Then, I just use trial and error to try to isolate the location in code that's failing, and the root cause of the failure.
If you just want a really quick way to find out what the error code means, you could use the "Error Lookup" tool packaged with Visual Studio (details here). Enter the hex value, and it will give you the string describing that error code.
Of course, once you know that, you've still got to figure out why it's happening.
A good way to look up error (hresult) codes is HResult Plus or welt.exe (Windows Error Lookup Tool).
I use logging internally in the COM-classes to see what is going on. Also, once the COM-class is loaded by the executable, you can attach the VS debugger to it and debug the COM code with breakpoints, watches, and all that fun stuff.
COM objects don't throw exceptions. They return HRESULTs, most of which indicate a failure. So if you're looking for the equivalent of an exception stack trace, you're out of luck. You're going to have to walk through the code by hand and figure out what's going on.