How to resolve Exception Error in C++ Builder - c++

I am in the process of converting an older DOS based 16-bit application into a current Windows console app. Each time I run the application in debug mode I receive the following error:
Project xxxx.exe raised exception class $C0000005 with message 'access violation at 0x004151f9: read of address 0x00000000'.
The following is the code line that blows up:
if ((argc < 1) || (strcmp(argv[1],"/?")) == 0) prg_syntax();
The code evaluates and should run the function to display the programs syntax but doesn't and instead throws the error.
I am using C++ Builder version (11.1.5).
Any help of where or how to overcome I would greatly appreciate.
Thanks,
Kent

By the convention argc cannot be lower than 1, because it will have at least the name / symbolic link to the execution (binary) file. In the case of no arguments passed to your program it will try to deference NULL pointer (the last element of argv[]).
if ((1 < 1) || (strcmp(NULL,"/?")) == 0) prg_syntax();
I believe you've wanted to do something like this:
if ((argc < 2) || (strcmp(argv[1],"/?")) == 0) prg_syntax();

Related

How to debug nondeterministic memory corruption?

I have a nondeterministic memory corruption problem. Because it's not always the same address, and it occurs only rarely, I can't simply watchpoint it with gdb.
The problem is a value changes between point A and point B in my program. The only thing that is supposed to change it is point C, which does not run in that time (at least not for the specific instance that experiences the unexpected modification).
What I'd like to do is something like mprotect the value at point A so the machine will trap if it is modified and unprotected it again around the intentional modification at point C. Of course, mprotect is not meant to be taken literally as I need it to work with word granularity.
Simply watchpointing at point A manually with gdb is far too much toil, the frequency of the problem is only about one per thousand.
Ideally, I would like a stack trace at the point that modifies it.
Any ideas?
Update: I just found out about rr http://rr-project.org/, a tool that can allegedly "determinize" non-determinism problems. I'm going to give it a go.
Update2: Well that was a short trip:
[FATAL /build/rr-jR8ti5/rr-4.1.0/src/PerfCounters.cc:167:init_attributes() errno: 0 'Success']
-> Microarchitecture `Intel Merom' currently unsupported.
You are experiencing undefined behavior and it's being caused somewhere else, debugging this is really hard.
Since you are apparently on Linux, use valgrind and it will help you a lot. If you are not on Linux or (OS X which is also supported by valgrind), search for equivalent memory error detection software for your system.
I found that it isn't that difficult to script gdb in a scripting language that you know (in my case, Ruby). This cuts down on the need to learn how to make proper gdb scripts!
The API between the target program and the script is that the target program has a blank function called my_breakpoint that accepts a single machine word as an argument. Calling my_breakpoint(1); my_breakpoint(addr); adds an address to the watch list while the same thing with the constant 2 removes an address from the watch list.
To use this, you need to start gdbserver 127.0.0.1:7117 myapp myargs, and then launch the following script. When the script detects a problem, it disconnects cleanly from gdbserver so that you can reconnect another instance of gdb with gdb -ex 'target remote 127.0.0.1:7117' and off you go.
Note that it's extremely slow to use software watchpoints like this; maybe someday something like this can implemented as valgrind tool.
#!/usr/bin/env ruby
system("rm -f /tmp/gdb_i /tmp/gdb_o");
system("mkfifo /tmp/gdb_i /tmp/gdb_o");
system("killall -w gdb");
system("gdb -ex 'target remote 127.0.0.1:7117' </tmp/gdb_i >/tmp/gdb_o &");
$fo = File.open("/tmp/gdb_i", "wb");
$fi = File.open("/tmp/gdb_o", "rb");
def gdb_put(l)
$stderr.puts("gdb_out: #{l}");
$fo.write((l + "\n"));
$fo.flush;
end
gdb_put("b my_breakpoint");
gdb_put("set can-use-hw-watchpoints 0");
gdb_put("c");
$state = 0;
$watchpoint_ctr = 1; # start at 1 so the 1st watchpoint gets 2, etc. this is because the breakpoint gets 1.
$watchpoint_nr = {};
def gdb_got_my_breakpoint(x)
$stderr.puts("my_breakpoint #{x}");
if ((x == 1) || (x == 2))
raise if ($state != 0);
$state = x;
gdb_put("c");
else
if ($state == 1)
raise if ($watchpoint_nr[x].nil?.!);
$watchpoint_nr[x] = ($watchpoint_ctr += 1);
gdb_put("watch *#{x}");
elsif ($state == 2)
nr = $watchpoint_nr[x];
if (nr.nil?)
$stderr.puts("WARNING: ignoring delete request for watchpoint #{x} not previously established");
else
gdb_put("delete #{nr}");
$watchpoint_nr.delete(x);
end
end
$state = 0;
gdb_put("info breakpoints");
$stderr.puts("INFO: my current notion: #{$watchpoint_nr}");
gdb_put("c");
end
end
def gdb_got(l)
t = l.split;
if ((t[0] == "Breakpoint") && (t[2] == "my_breakpoint"))
gdb_got_my_breakpoint(t[3][3..-2].to_i);
end
if (l.start_with?("Program received signal ") || l.start_with?("Watchpoint "))
gdb_put("disconnect");
gdb_put("q");
sleep;
end
end
while (l = $fi.gets)
l = l.strip;
$stderr.puts("gdb_inp: #{l}");
gdb_got(l);
end

How to investigate and fix libpjsua2.so crash

SIGSEGV SEGV_MAPERR at 0x00000008
0 libpjsua2.so 0x56585a88 pj::Call::getInfo() const
1 libpjsua2.so 0x56546b44 std::allocator<pj::CallMediaInfo>::allocator()
I'm using pjsip for one of my hobby project(complies with GPL). Above you can see the stacktrace received from crashlytics. I'm using Java wrapper for pjsip.
There are a lot of users(50 %) affected by this error, however I'm not able to reproduce it on my local devices.
Not sure but I suspect that following java call lead to error. Which call C++ via JNI
public void notifyCallState(MyCall call) {
if (currentCall == null || call.getId() != currentCall.getId())
return;
CallInfo ci;
try {
ci = call.getInfo();
} catch (Exception e) {
ci = null;
}
Message m = Message.obtain(handler, MSG_TYPE.CALL_STATE, ci);
m.sendToTarget();
if (ci != null && ci.getState() == pjsip_inv_state.PJSIP_INV_STATE_DISCONNECTED) {
currentCall = null;
}
}
Code snippet is taken from examples which come from psjua download. Link to http repo. My code is the same. Any help highly appreciated
From the stacktrace is looks like call is null, and getId method is at 0x8 offset.
If that's really the case, the fix is to make sure notifyCallState isn't called with null argument, or to check it inside the method, i.e.:
if (call == null || currentCall == null || call.getId() != currentCall.getId())
return;
Your program is most likely hitting some sort of memory corruption and most likely heap memory. Following observations points towards that.
I'm not able to reproduce it on my local devices. This is common symptoms of memory corruption.
stack-trace includes std::allocator which indicates that program has been terminated while using(creating/deleting/accessing) the heap memory.
Recommendation
We should try to review the code logic and whether this program uses Interop service in correct way.I do not have much idea regarding this however it looks like your program logic does have JAVA/C++ interaction. If we are lucky we might get something obvious here and we are done.
If the stack-trace are after effect of something else, then we are in trouble we might have to take approach suggested in below posts.
Windows Platform
https://stackoverflow.com/a/22074401/2724703
Linux Platform
https://stackoverflow.com/a/22658693/2724703
Android Platform
https://stackoverflow.com/a/22663360/2724703
You may want to refer the above posts to get the idea about how to approach on such problems. As per my understanding, android platform does not have dynamic tools so you might have to use some versions(debug/additional logging) of your library.
I do hope that, above information might be useful and would have given some guidelines to approach your problem.

If statement compatibility issue in Swift (it worked before)

i reopened a project i stop working on for some days and without edditing any line, when i tried to run it, it gave me two errors i never saw before and i persoanlly think they make no sense. Please help me, the code is like this:
if normals == true && numberOfTaps > highScoreN.integerForKey("highscoren") || normals == 1 && highScoreN.integerForKey("highscoren") == 0
It gives me this error: "Cannot invoke '==' with an argument list of type '($T16, $T31)'"
and in another line, which is practically the same:
if pros == true && numberOfTaps > highScoreP.integerForKey("highscorep") || pros == 1 && highScoreP.integerForKey("highscorep") == 0
It gives me this error: "Cannot invoke '==' with an argument list of type '($T16, $T31)'"
I repeat, it had worked properly some days before, i dont know why it isn't..
Thank you so much!
PSD:// highScoreP and highScoreN are NSUserDefault type
The error is on the == in both lines, so that narrows it down. The only place you have == is comparing the normals variable to true and 1. Swift is very type safe, so your normals variable cannot be both true (a boolean) and 1 (an Int). Check the type of your normals variable and proceed form there.

Unhandled exception VS2010 C++

I am trying to make a socket on windows to connect to a server.
I am using the code from msdn's website, the winsock client code.
(Link: msdn.microsoft.com/en-us/library/windows/desktop/ms737591(v=vs.100).aspx )
In any case, when I try debugging said code I get the error message:
Unhandled exception at 0x58a714cf (msvcr100d.dll) in Application.exe: 0xC0000005: Access violation reading location 0x00000032.
It asks me if I want to break or continue, if I continue the same error message simply keeps popping up. If I press break it takes me to line 1643 in the file output.c .
Simply put, I have no idea about what to do to make it work, and I'd appreciate any help given.
EDIT:
A reply to all comments given thus far:
The surrounding relevant code in output.c is:
if (flags & (FL_LONG|FL_WIDECHAR)) {
if (text.wz == NULL) /* NULL passed, use special string */
text.wz = __wnullstring;
bufferiswide = 1;
pwch = text.wz;
while ( i-- && *pwch )
++pwch;
textlen = (int)(pwch - text.wz);
/* textlen now contains length in wide chars */
} else {
if (text.sz == NULL) /* NULL passed, use special string */
text.sz = __nullstring;
p = text.sz;
while (i-- && *p) //THIS IS WHERE IT BREAKS
++p;
textlen = (int)(p - text.sz); /* length of the string */
}
This is not code that I have written but innate code that already exists.
EDIT NR 2:
This is a printscreen displaying my call stack.
I do not have 10 reputation so I cannot show the image, so here is a link to the image:
http://tinypic.com/r/5n6ww9/5
On it you can see my call stack
The file output.c has the code that handles the printf family of functions.
The fact that you have an error here is probably due to a malformed printf function call in your code. Maybe you have specified an invalid print format or have not provided enough arguments.
When your program crashes, click Break and look at the call stack in the debugging windows to see where - in your code - the function is called, and with what arguments.
I suspect you are trying to print a NULL string or something. When you have found the printf call (if that's what it is), edit your question to show that section of source code and/or use the debugger to examine the variables used a arguments to the function and make sure they are all correct.
Without seeing the code that you've written, at the location of the crash, it's not possible to give a more precise answer.
Or you may insert a null string to CString.format like below:
CString str;
str.format("%s"); //A null string
where it should be
str.format("%s",mes);
where mes is char mes[20] for example
or any other variable
So the point is there may be some mistake in CString.format or Printf
Good Luck.

Why cv::meanStdDev function fails with exception on debug

I'm developing an opencv app for the ios platform. I have opencv compiled by my self for debug and release schemes, but when I try to run the cv::meanStdDev function with Debug scheme, the application fails with an exception ( with Release it works fine ).
The test function is very simple:
float list[] = {1.2,1.2,1.3,0.3,6.5,2.2,0.9,0.8,0.9};
cv::Mat test(1,9,CV_32F, list);
cv::Scalar mean1, stddev1;
cv::meanStdDev(test, mean1, stddev1);
printf("[%f, %f]", mean1.val[0], stddev1.val[0]);
This function works properly on Release scheme, but on Debug, it throws an exception like this:
OpenCV Error: Assertion failed (dims == 2 && ((sizes[0] == sz.height && sizes[1] == sz.width) || (allowTransposed && sizes[0] == sz.width && sizes[1] == sz.height))) in create, file /Users/jgoenetxea/libraries/OpenCV-2.4.0/trunk/opencv/modules/core/src/matrix.cpp, line 1375
terminate called throwing an exception
This line is a 'create' function of the matrix class.
In this point, the kind() function gives different values in Debug and Release schemes for the same matrix. When Debug scheme is selected, because of the result of this kind() function, the execution checks some data with a CV_Assert function invocation, and then fails.
Any ideas? Someone know what can I check?
Is this your entire program?
If no, there is a possibility of heap corruption, which is very common on OpenCV due wrong access to Mat elements.
Ex:
Mat<uchar> mat(2,2);
mat.at<float>(1,1)=0.1;
If there is such code before the program segment you wrote, there may be a chance that your heap is corrupted, then you must fix it.
On release mode you may be corrupting another area that does not interfere in this part of code, but in debug it looks like it does.
But if this is your entire code, i can't help too much... it looks right to me.