Printing a double to std::cout results in Segmentation fault (C++) - c++

I am new to C++ and want to print out a double value. It is not that I actually need to print that value, I just want to know what is going wrong here.
This is my code (HelloWorld.cpp):
#include <iostream>
int main() {
double i = 5.5;
std::cout << i << std::endl;
return 0;
}
Executing this with the debugger attached results in the following error:
Thread 1 hit Breakpoint 1, main () at src/HelloWorld.cpp:4
4 double i = 5.5;
Thread 1 received signal SIGSEGV, Segmentation fault.
0x00000000929ba260 in ?? ()
When I put a breakpoint in there, creating and assigning the variable is no problem. The error only occurs once the program is supposed to print that value. Executing the exe without the debugger results in no output at all. The same happens when I replace the double with a long double or float. Printing anything else works fine (Strings, char, int, short, etc.).
I am using Visual Studio Code and MinGW (x86_64-8.1.0-posix-seh-rt_v6-rev0). VS Code is using following files for compilation / debugging:
c_cpp_properties.json
launch.json
tasks.json
And here you can see the complete output, in case that helps.
Any Idea what I am doing wrong here? Thank you.
EDIT:
When compiling manually using g++ -g .\src\HelloWorld.cpp -std=c++11 -o HelloWorld.exe (or just g++ .\src\HelloWorld.cpp -o HelloWorld.exe) and running that from the console, the same happens (no output).
I installed MinGW from here using the following settings:
Version: 8.1.0
Architecture: x86_64
Threads: posix
Exception: seh
Build revision: 0
EDIT 2:
Found the problem. There was an old version of gcc lurking in my PATH (maybe from Visual Studio or MSSQL Server?). I just move the current gcc to the top of PATH and now it's working fine. Thank you all for your help!

As many pointed out, this should usually work. The problem was with my setup: I had an old version of gcc somewhere in my PATH variable (version 4.1). Moving the path of the newer version to the beginning of PATH resolves the issue. Thank you all for helping.
To check weather the same happens to you you can do the following: execute g++ --version in your project directory. Compare this with the output of g++.exe --version when you are in the directory where gcc is installed (for me, this was C:\Program Files\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin).

Related

gdb <error reading variable> for any string object

Lets take this very simple program here for example:
// test.cpp
#include <string>
#include <iostream>
using namespace std;
int main() {
string str = "Hello";
cout << str << endl;
return 0;
}
now I compile this code with g++ compiler:
g++ -g test.cpp -o test.exe
now I am trying to debug this with gdb:
gdb test.exe
after I set breakpoint on main and then reach the line return 0, I try to see what is in the string str. But I cannot print it in the console. It says <error reading variable>. Not only in gdb console, even Visual Studio Code UI using gdb gives the same output.
Here is a screenshot of my console:
I have searched for this everywhere and the only relevant question I found was this, which did not work.
I also found this post on github VS Code repo issues. The fix suggested there might work I am not sure, I cannot find the setting that he suggested on my Windows 11 machine.
How do I read the value in the string in debug mode?
Edit
After #ssbssa suggested me to update my gcc, I used MSYS2 to get the latest gcc, g++, and gdb versions. Now I have gdb 12.1. Now it is not showing the old error anymore but now it says "Converting character sets: Invalid argument". Still struggling to get it to work.
First run your program with gdb like so:
gdb test.exe
Now inside the command line interface run the command:
set charset UTF-8
This should temporarily fix your problem. The only inconvenience might be that you need to run this line every time you debug on your command prompt with GDB.
I noticed that you are also using Visual Studio Code. You can install C++ extensions for VS Code and there you can add the command set charset UTF-8 in the launch.json setupCommands array as shown here. This way you can debug your application faster.

WASM link error: function signature mismatch

I've been using WASM via emscripten for a few weeks now and had been making good progress, until this error:
exception thrown: RuntimeError: function signature mismatch,RuntimeError: function signature mismatch
This started happening in code that previously worked and seems to be something to do with WASMs lack of support for 64bit integers in javascript and the offsets used in file management. I've made an isolated case:
#include <iostream>
int main(int argc, char const *argv[])
{
char test[30];
std::cout << __LINE__ << std::endl;
FILE *f = fopen("minimal_call_dispatch.cpp","ra");
std::cout << __LINE__ << std::endl;
fseek(f, 100, SEEK_SET);
std::cout << __LINE__ << std::endl;
fclose(f);
std::cout << __LINE__ << std::endl;
return 0;
}
building with:
call emcc -o ./test.js test_file.cpp -s WASM=1 -s NO_EXIT_RUNTIME=1 -std=c++1z
Which outputs '6\n8\n' before failing on 'fseek' due to the mentioned error.
Somewhere along the line, I suspect that wasm is trying to use headers that communicate with javascript that have 64bit integers instead of 32bit ones but I can't see how that could have happened.
I'm going to try re-installing emscripten but even if that works, I'd like to get a better idea of what's causing this.
As a work around, does anybody know how to get emcc to ignore worries over 64bit integers and silently convert them to 32bit? I'm not looking to address more than 3gigs of ram, after all.
You got the error simply because your code is wrong.
You really don't need to worry about 32bit/64bit stuff. The current WebAssembly spec do not have 64-bit machine and it only have 32-bit addresses (but it supports 64-bit integer i64 internally and calculates 64-bit integers well. It just doesn't have 64-bit addresses.)
This means that the compiler is already knows the target machine is 32-bit and size_t will be 32-bit as will.
In the comments, I asked if you want to open the file or want to create the file. This is important because using "ra" with fopen() will cause segmentation fault when the file doesn't exist because of r flag!
Okay, lets try this in the native environment.
g++ test_file.cpp -o test.out
running ./test.out will prints the following if test_file.cpp doesn't exist:
6
8
[2] 14464 segmentation fault (core dumped) ./test.out
So your code is wrong, but why Emscripten throws the error differently? When you use emcc without debugging flags like -g, it will have the minimized environment that doesn't catch errors like segfault because such smart runtime will increase the binary size which is critical in the web environment. As a result the runtime keeps running ignoring segfualt and it will end up with a random error. So function signature mismatch doesn't mean anything.
You can build it using debugging-related options:
emcc -o ./test.html test_file.cpp -s WASM=1 -std=c++1z \
-g4 -s ASSERTIONS=2 -s SAFE_HEAP=1 -s STACK_OVERFLOW_CHECK=1 \
--source-map-base http://your_server_ip:port/
Then opening test.html you will see the correct error now:
exception thrown: RuntimeError: abort(segmentation fault) at Error
Now you won't get the misleading errors like signature mismatch :)
By the way, replace fopen("minimal_call_dispatch.cpp","ra"); with fopen("minimal_call_dispatch.cpp","a"); will fix the error.
With the correct --source-map-base server IP settings, you will have a better debugging experience. For example, you will get the source test_file.cpp in the browser so that you can set breakpoints to the .cpp file.
Have fun with debugging :)

OpenCV program compiles but doesn't run

I am working on Windows 8 with OpenCV 2.4.13 and MinGW 4.9.
I wrote a simple and small opencv program to check if everything was installed properly. Following is the code:
#include <opencv2/highgui/highgui.hpp>
int main () {
printf("in main\n");
for (int i = 0; i<10; i++) {
printf("here\n");
IplImage * image = cvLoadImage("C:/{...}/test.jpg");
cvReleaseImage(&image);
}
return 0;
}
I compiled it with the following command at the command prompt:
g++ -o test test.cpp -LC:\{...}\opencv\build\x64\vc11\lib -lopencv_core2413 -lopencv_highgui2413 -IC:\{...}\opencv\build\include
{...} is the path to the specified folder/file.
This command runs properly and compilation is successful without any errors. However, when I run it with:
test
in main and one here gets printed after which I get the error message as 'test.exe has stopped working. Windows is looking for a solution.'
What all I have tried:
For installation of OpenCV, ran the downloaded opencv executable file (which extracts all files) and added the system variable OPENCV_DIR and edited the system PATH for location of DLLs (which reside in %OPENCV_DIR%\bin) as per:
http://docs.opencv.org/2.4/doc/tutorials/introduction/windows_install/windows_install.html#installation-by-using-the-pre-built-libraries
Tried adding the required DLLs in the same directory as the .exe.
Tried doing the whole thing from vc12 directory.
After the error message appears, it gives an option of debugging. On pressing that, the Just In Time Debugger opens up and says 'An unhandled win32 exception occurred in test.exe'. I googled this and tried inspecting the registry key as directed here
https://support.microsoft.com/en-us/kb/811191
but it was already properly set. So, there was nothing for me to change in that.
Nothing is working for me at all. Please let me know if any more information is required. I'm desperately looking for a solution to this.
For those who might be encountering the same problem, I compiled the program with OpenCV dynamic (.dll) libraries instead of the .lib files and it ran just fine at runtime for some reason.

Why are all my C++ programs exiting with 0xc0000139?

I am trying to teach myself to program in C++ and am using Cygwin on Windows with g++ installed. Everything was going swimmingly until I started to declare string variables. Using string literals with cout causes no issues, but as soon as I declare a string variable the program will no longer run.
#include <iostream>
#include <string>
int main ()
{
std::string mystring = "Test";
std::cout << mystring;
return 0;
}
The preceding code compiles without issue, but when run produces no output. GDB provides me with the following:
(gdb) run
Starting program: /cygdrive/c/Projects/CPP Test/string.exe
[New Thread 8416.0x2548]
[New Thread 8416.0x2510]
[New Thread 8416.0x1694]
[New Thread 8416.0x14f4]
[Thread 8416.0x1694 exited with code 3221225785]
[Thread 8416.0x14f4 exited with code 3221225785]
During startup program exited with code 0xc0000139.
From what I have managed to gather this is some sort of entry point issue with a DLL, but I could be completely wrong.
Does anyone know what I have done wrong or what I have misconfigured and how to fix it?
Well I'm not sure what the problem was exactly (if anyone knows I'd be grateful!), but I was able to solve it for myself by downgrading from GCC 5.2.0 to GCC 4.9.3.
Error code 0xc0000139 is issued when windows is failing to load a dll file.
A possible cause is having several distinct versions of the compiler installed.
This may happen when you install on your PC several SWs that come with embedded mingw - e.g., Visual C, Vagrant, Omnet++.
For me, a simple workaround was to run the program in a different way: Instead of running my SW (Omnet++) from the GUI, I ran it from the mingwenv.cmd command line. This solved the problem.
A smarter solution may be found in the answer of Rudolf from Sep 18, 2017, 11:35:13 AM here. In short, he suggests carefully temporarily changing the system's environment variables; and thus, finding the conflicting erroneous dll's, and removing them.
In the answer of Tian Bin below it you can see Figs. explaining it.
I had the same problem while mixing up a Release and a Debug build, using Windows 10, mingw compilation and gcc-8.1.0.
I solved it by cleaning and recompiling everything:
cd ${MY_BUILD}
make clean
cmake ${MY_SOURCE} -DCMAKE_BUILD_TYPE=Debug
make -j4
gdb ./bin/my_program.exe # -> works
./bin/my_program.exe # -> no more problem

Error when running OpenNI 2 class ( gcc 4.7.2 / ubuntu 12.10 )

I'm trying to compile an run a very basic program given below (test.cpp) which calls the OpenNI class. You can see the files and dirs they're in here. Sorry that some characters screws up a little bit in the browser's encoding. I'm using the linux command: tree, if you know a better command tell me and I will update it.
File Structure
I'm following the guide here, see "GCC / GNU Make".
#include < stdio.h >
#include < OpenNI.h >
using namespace openni;
int
main ( void )
{
Status rc = OpenNI::initialize();
if (rc != STATUS_OK)
{
printf("\nInitialize failed\n%s\n", OpenNI::getExtendedError());
return 1;
}
printf("Hello, world!\n");
return 0;
}
Here is what I'm running in the command line to compile it (gcc 4.7.2):
gcc test.cpp -I../OpenNI-2.0.0/Include -L/home/evan/Code/OpenNi/Init -l OpenNI2 -o test
This works fine but when I run ./test I get the following error:
Initialize failed
DeviceDriver: library handle is invalid for file libOniFile.so
Couldn't understand file 'libOniFile.so' as a device driver
DeviceDriver: library handle is invalid for file libPS1080.so
Couldn't understand file 'libPS1080.so' as a device driver
Found no valid drivers in './OpenNI2/Drivers'
Thanks, any help would be much appreciated.
Instructions from your guide says, that
It is highly suggested to also add the "-Wl,-rpath ./" to your linkage command. Otherwise, the runtime linker will not find the libOpenNI.so file when you run your application. (default Linux behavior is to look for shared objects only in /lib and /usr/lib).
It seems you have exactly this problem -- it can not find some libraries. Try to add proper rpath (seems to be /home/evan/Code/OpenNi/Init/OpenNI2/Drivers in your case) to your compilation string.
I had the same issue after compiling this little "Hello World" with Eclipse and trying to run it in the command line.
The "Wl,-rpath=./" thing did not work for me.
As also discussed here it worked for me after setting some env. variables before execution:
export LD_LIBRARY_PATH="/path/to/OpenNI2:$LD_LIBRARY_PATH"
export OPENNI2_DRIVERS_PATH="/path/to/OpenNI2/Drivers"
export LD_LIBRARY_PATH="/path/to/OpenNI2/Drivers:$LD_LIBRARY_PATH"
Somewhere I got the info that the first two lines should be enough but it was the third line which is important. I does also work just with the third line.