C++ runtime errors in CodeBlocks when printing strings with cout << - c++

I recently started using CodeBlocks and began encountering odd runtime errors which I have traced back to printing strings using cout <<. For example, even the following..
#include <string>
#include <iostream>
int main()
{
std::string str;
str = "Hi!";
std::cout << str << std::endl;
return 0;
}
results in an error. It will compile fine (using Borland) but when I run it I get a pop up window saying 'test.exe has stopped working' and in the console I get the message:
Process returned -1073741819 (0xC0000005) execution time : 1.526 s
Press any key to continue.
It compiles and runs fine in MS Visual C++ and with G++ in Ubuntu.. any thoughts would be greatly appreciated!
Cheers,
Weatherwax

My one-off comment ended up helping solve the problem so here it is packaged up as an answer for future users:
This guy had a similar issue and it ended up being a linker issue which he
fixed. The fix is the last post in the thread, although reading the
whole thread could be useful for you.
Long Story short: Borland compiler is a bit dated and annoying to use. Ended up being a linker issue within borland. Better off using a different compiler like GCC/G++ or Visual Studio compiler.

This answer is here to elaborate on the root cause of the issue.
The reason for your crashing program is because the wrong runtime library is being linked. Specifically, your example is compiled as a single threaded object file(the default) but the linking step is using the multithreaded cw32mt.lib runtime -- the "mt" suffix at the end means multithreaded.
The solution is to make sure the runtime your program is compiled to use matches with the runtime you're linking against. A few ways to do this.
Important bcc32 compile switches:
-tW Windows GUI program. WinMain() is expected
-tWC Windows Console program. main() is expected. default.
-tWR Use dynamically linked runtime. Absence implies static runtime linkage.
-tWM Use multithreaded runtime. Absence implies single thread.
Compiling your example program as single threaded like this works:
bcc32 -oexample.obj -c example.cpp
ilink32 -ap example.obj c0x32, example.exe,, cw32.lib import32.lib,,
or you can compile it as multithreaded like this(note the -tWM switch matching up with cw32mt.lib):
bcc32 -tWM -oexample.obj -c example.cpp
ilink32 -ap example.obj c0x32, example.exe,, cw32mt.lib import32.lib,,
A third approach that is easier and less error prone is to not call the linker yourself. Instead, let the compiler drive the linker indirectly(similar to gcc):
bcc32 -tWM -oexample.obj -c example.cpp
bcc32 -tWM example.obj -eexample.exe
For your simple example, it can even be shortened to:
bcc32 -eexample.exe example.cpp
Lastly, you can pass the -tW switch multiple times. For example, this command compiles your example as a console program with multithread support and dynamic runtime linkage:
bcc32 -tWM -tWR -tWC -eexample.exe example.cpp
The produced example.exe executable is much smaller and its import table has an entry for CC3250MT.DLL confirming that the borland runtime is dynamically linked.
We should not assume that a non-functioning program is caused by nonconformity to the standard or a bug in the tool we're using without first investigating user error as a potential cause (even though in this case it's tempting to do so). In the OP's case, the code::block IDE didn't have the right commands setup for the toolchain being used.

Related

Instruments won't profile code when a specific library is linked in the C++ binary, OSX

I'm having an issue with Instruments. My program requires I link a library and use some of it's functions. However, when trying to use Instruments it quits profiling within 100ms and gives me some garbage output that doesn't represent what's going on when my program runs correctly. I created a small program to see if my instruments version was working. The only issue seems to be when a binary is linked with this particular library (exodus), Instruments won't profile the code and exits early. I tried linking the small test program against other dylib's, and there was no issue. I even uninstalled an older version of XCode I had and installed the latest one to no avail.
When I build the following simple program without the exodus library, instruments runs it fine.
"main.cpp"
#include <iostream>
int func() { std::cout << 1; }
int main()
{
while(true) { func(); }
}
clang++ -g main.cpp -o main
Instruments output looks like this:
Now if I built the test program like this:
clang++ -g main.cpp -o main -L/opt/local/lib/ -lexodus
Instruments only runs for 1ms, despite the program being the exact same.
What might the issue be here? Any ideas on circumventing it? Any other information I can provide that might be useful? I don't need any profiling information regarding exodus, I just need to see what my own code is doing.
Thanks for any help

Compile a C++ code snippet using G++ dynamically

Working on a C++ based application, it takes user input and generates a C++ function and compile it to create a .so file and links the function to the main application. Currently had to call an external command "g++" to do it. Wonder if it's possible to call some kind of function, say, "compile" which takes as input an code snippet and produces an .so. More precisely, I need a function that has the following syntax:
sizeOfObjBuf = compile(codeBuf, objBuf);
First parameter is a null terminated string containing a code snippet, the second parameter is the output buffer that hold the compiled code and it returns the size of size of compiled code.
The whole idea is to get rid of dependency on an external program (g++) so the application can run on any Linux system (even when it doesn't have g++ installed).
Thanks.
I'm afraid the answer is "no".
You could implement that function by executing G++ (or some other compiler) in a separate process and waiting for it to finish, but that still requires the user to have a compiler installed.
You can't compile C++ code without a C++ compiler.
I am not going to do the research to figure out how it is done, but I believe the LLVM C++ compiler can be used in this way. All of the parts of LLVM are designed to run as a library, in theory.
OK, a tiny bit of research and I found this: http://clang.llvm.org/docs/LibTooling.html

Internal exceptions in shared library terminate end user application

I am building a shared library which uses Boost.thread internally. As a result, Boost.system is also used since Boost.thread depends on that. My shared library exports a C interface, so I want to hide all my internal exception handling and thread usage etc from the end user. It is supposed to be a black box so to speak. However, when I link with a client application, while the program runs fine - as soon as it is time to stop the processing by invoking a library function I get:
terminate called after throwing an instance of 'boost::thread_interrupted'
I catch this exception internally in the library, so I have no idea why it is not actually being caught. The end user's program is not meant to know about or handle Boost exceptions in any way. When building the shared library, I use static linking for both Boost.thread and Boost.system so the outside world is never meant to see them. I am on GCC 4.7 on Ubuntu 12. On Windows, I have no such problems (neither with MSVC or MinGw).
(EDIT)
I am editing the question to show a minimalistic example that reproduces the problem, as per the requests in the comments.
Here first is the code for testlib.cpp and testlib.h.
testlib.cpp:
#include <boost/thread/thread.hpp>
void thread_func()
{
while(1)
{
boost::this_thread::interruption_point();
}
}
void do_processing()
{
// Start a thread that will execute the function above.
boost::thread worker(thread_func);
// We assume the thread started properly for the purposes of this example.
// Now let's interrupt the thread.
worker.interrupt();
// And now let's wait for it to finish.
worker.join();
}
And now testlib.h:
#ifndef TESTLIB_H
#define TESTLIB_H
void do_processing();
#endif
I build this into a shared library with the following command:
g++ -static-libgcc -static -s -DNDEBUG -I /usr/boost_1_54_0 -L /usr/boost_1_54_0/stage/lib -Wall -shared -fPIC -o libtestlib.so testlib.cpp -lboost_thread -lboost_system -lpthread -O3
Then, I have the code for a trivial client program which looks as follows:
#include "testlib.h"
#include <cstdio>
int main()
{
do_processing();
printf("Execution completed properly.\n");
return 0;
}
I build the client as follows:
g++ -DNDEBUG -I /usr/boost_1_54_0 -L ./ -Wall -o client client.cpp -ltestlib -O3
When I run the client, I get:
terminate called after throwing an instance of 'boost::thread_interrupted'
Aborted (core dumped)
I am not explicitly catching the thread interruption exception, but according to the Boost documentation Boost.thread does that and terminates the given thread only. I tried explicitly catching the exception from within the thread_func function, but that made no difference.
(End OF EDIT)
(EDIT 2)
It is worth noting that even with -fexceptions turned on, the problem still persists. Also, I tried to throw and catch an exception that is defined in the same translation unit as the code that catches and throws it, with no improvement. In short, all exceptions appear to remain uncaught in the shared library even though I definitely have catch handlers for them. When I compile the client file and the testlib file as part of a single program, that is to say without making testlib into a shared library, everything works as expected.
(End OF EDIT 2)
Any tips?
I finally figured it out. The -static flag should never be specified when -shared is specified. My belief was that it merely told the linker to prefer static versions of libraries that it links, but instead it makes the generated dynamic library unsuitable for dynamic linking which is a bit ironic. But there it is. Removing -static solved all my problems, and I am able to link Boost statically just fine inside my dynamic library which handles exceptions perfectly.
Maybe this?
If you have a library L which throws E, then both L and the
application A MUST be linked against X, the library containing the
definition of E.
Try to link executable against boost, too.
A shared library that itself includes statically linked libraries is not such a good idea, and I don't think that this scenario is well supported in the GNU toolchain.
I think that your particular problem arises from the option -static-libgcc, but I've been unable to compile it in my machine with your options. Not that linking statically-dinamically to libpthread.so sounds as such a good idea either... What will happen if the main executable wants to create its own threads? Will it be compiled with -pthread? If it is, then you will link twice the thread functions; if it isn't, it will have the functions but not the precompiler macros nor the thread-safe library functions.
My advice is simply not to compile your library statically, that's just not the Linux way.
Actually that should not be a real problem, even if you don't want to rely on the distribution version of boost: compile your program against the shared boost libraries and deploy all these files (libboost_thread.so.1.54.0, libboost_system.so.1.54.0 and libtestlib.so) to the same directory. Then run your program with LD_LIBRARY_PATH=<path-to-so-files>. Since the client is not intended to use boost directly, it doesn't need the boost headers, nor link them in the compiler command. You still have your black box, but now it is formed by 3 *so files, instead of just 1.

MinGW and std::thread

So I've been trying to get the following code to compile and run on Windows by using a MinGW compiler.
#include <iostream>
#include <thread>
void test()
{
std::cout << "test" << std::endl;
}
int main()
{
std::thread t(test);
}
I'm compiling with the following command:
g++ -std=c++11 test.cpp -o test.exe
Now the problem is the version of MinGW one should use and I've tried about all the versions I know of.
MinGW-builds: thread-win32
MinGW-builds: thread-posix
MinGW-w64: stdthread experimental rubenvb
MinGW-w64: stdthread experimental rubenvb 4.7
Number 1 doesn't work, since GCC apparently only supports pthread stuff internally.
Number 2 does compile and it essentially even outputs test (see the last line of the output), but it also crashes with the error:
terminate called without an active exception
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
test
Number 3 and 4 again do compile, but they don't output test and instead instantly crashes, but with a more descriptive output:
terminate called after throwing an instance of 'std::system_error'
what(): Enable multithreading to use std::thread: Operation not permitted
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
Google brought me of course to the GCC bug tracker and some other posts, that suggested to use -pthread, which doesn't help at all.
I've also tried manually linking against winpthread and pthread, but that doesn't do anything either.
There's also no difference between -std=c++11 and -std=gnu++11...
I'm really lost right now and don't know, if it's at all possible to get a MinGW version, that supports std::thread, but maybe I'm just overlooking some compiler flags. I hope someone out there can help me!
You forgot to join your thread:
t.join();
FYI, there is already a native win32 implementation of std::thread and sync primitives. It is a header-only library and works on any C++11 compliant version of MinGW.
https://github.com/meganz/mingw-std-threads

AVG Access Denied warning when running the simplest C++ program

I am running a very simple C++ program:
#include <list>
#include <vector>
int main(int argc, char **args) {
}
I go to the command prompt and compile and run:
g++ whatever.cpp
a.exe
Normally this works just fine. It compiles fine, but when I run it it says Access Denied and AVG pops up telling me that a threat has been detected Trojan Horse Generic 17.CKZT. I tried compiling again using the Microsoft Compiler (cl.exe) and it runs fines. So I went back, and added:
#include <iostream>
compiled using g++ and ran. This time it worked fine.
So can anyone tell me why AVG would report an empty main method as a trojan horse but if the iostream header is included it doesn't?
UPDATE:
I added a return statement to the main method and now I find that I only get the error if I return 0. Any other return value and it seems to work fine.
What's going on here?
You're not the first person to encounter false positives by antivirus software.
What probably happened is that the antivirus heuristics tripped up on the standard runtime libraries present in your programs, since malware uses them as well. Of course, legitimate software uses them too! The fact that it didn't trip up on iostream probably means that iostream isn't very popular among malware writers.
If you only want to overcome the problem as fast as possible,
just put the folder of the executables into AVG's whitelist.
My preferred steps:
For safety's sake, you should send your executable
to an online virus/malware scanner like these:
www.virustotal.com : VirusTotal - Free Online Virus and Malware Scan
virusscan.jotti.org/en : Jotti's malware scan
if they report 'false positive', then insert the path of the compiled executables
into AVG's whitelist,
so it doesn't scan that folder.
I'm not conversant with AVG, but every antivirus
has an option to exclude files from scan.
If you're brave enough, debug the executable and find the causing call.
An alternative solution may be to virtualize a lightweight linux system,
install gcc (with g++, of course) on it, and use that "g++ dedicated environment"
to
develop your commandline apps.
// The 1st step is a sum-up of this conversation.
// If you send me the source and the 'infected' executable that you compiled, then I'll check it.
// The missing return statement in the (C++) main function means returns 0.