g++ malloc error when linking with libmx and using std::stringstream - c++

The simplest example is the following program, linked with libmx (-lmx) (for MATLAB support) on OS X Yosemite, compiled with g++4.9.1 from macports:
#include <sstream>
int main()
{
std::ostringstream ostr;
// ostr << " "; // if I un-comment this line no more malloc error
}
I realized that at ostr destruction (just before exiting the program), I get a malloc runtime error of the form:
testcpp(5362,0x7fff7d2af300) malloc: *** error for object 0x1055b6270:
pointer being freed was not allocated *** set a breakpoint in malloc_error_break to debug
If, on the other hand, I uncomment the second line in main() and write something to the ostringstream, then the program exits happily with no more error. This happens only with g++, clang++ compiles and runs it without any problems. Anyone knows if this is a g++-related issue or a libmx one?
PS: if I am not using -lmx flag on linking, then there is no more malloc error.

I guess it's better to comment on this separately. As I said, I'm having troubles reproducing your error. I'm on Ubuntu Linux 14.04 64 bits with g++ 4.8.2 and I downloaded the Matlab Compiler Runtime v83 and v84 for Linux 64 bits.
The source I am compiling is the following:
#include <sstream>
int main()
{
std::ostringstream ostr;
// ostr << " "; // if I un-comment this line no more malloc error
}
And the following commands run fine (2014 a and b):
g++ -L/opt/MATLAB/MCR/v83/runtime/glnxa64 -Wall malloc_gcc_matlab.cpp -o malloc_gcc_matlab && ./malloc_gcc_matlab
g++ -L/opt/MATLAB/MCR/v84/runtime/glnxa64 -Wall malloc_gcc_matlab.cpp -o malloc_gcc_matlab && ./malloc_gcc_matlab

Related

How to include <numbers> header file and use std::numbers

running on version 11.1.0 of gcc and g++. Every time I run this code I run into issues it says std::numbers was not declared. I tried running g++ randomCodeWhileReading.cpp -o main-std=c++20 within my terminal (im running ubuntu linux) and still no change. Here is the code in question:
#include <iostream>
#include <numbers>
int main()
{
const long double pi {0};
const long double pi2 {0};
pi = std::numbers::pi_v<long double>;
pi2 = std::numbers::pi_v<long double>;
std::cout << pi << std::endl << pi2;
}
Just wanted to see the numbers module in action nothing else. (is it even called a module or is it a header file?)
EDIT 10/6/21:
The modifying a constant variable has been fixed. However, this code still wont run on my computer. Namely, the #include <numbers> does not seem to work on my machine it throws an error even when using -std=c++20. I am running gcc and g++ version 11.1 See error below:
gcc ex2_03.cpp -o -std=c++20
ex2_03.cpp: In function ‘int main()’:
ex2_03.cpp:22:65: error: ‘std::numbers’ has not been declared
22 | const double pond_diameter {2.0 * std::sqrt(pond_area/ std::numbers::pi)}; //find diameter by finding radius & multiplying by 2
|
however I was unable to replicate using godbolt.org (similar program not the same but uses as well). Clearly, it seems that this is an issue with my machine. How would I go about fixing this?
EDIT 10/8/21:
I ran the code again using more flags and changing -std=c++20 to -std=c++2a this was what was returned:
chris#chris-Aspire-E5-576G:~/Desktop/programming/c++/Learning$ ls
ex2_02 HelloWorld randomCodeWhileReading textbookExample1
ex2_02.cpp HelloWorld.cpp randomCodeWhileReading.cpp textbookExample1.cpp
ex2_02.o HelloWorld.o randomCodeWhileReading.o textbookExample1.o
ex2_03 main textbookDebug textbookOutputNameAndAge.cpp
ex2_03.cpp outputNameAndAge textbookDebug.cpp
ex2_03.o outputNameAndAge.o textbookDebug.o
chris#chris-Aspire-E5-576G:~/Desktop/programming/c++/Learning$ g++ -g -Wall -pedantic -std=c++2a -o randomCodeWhileReading.cpp
g++: fatal error: no input files
compilation terminated.
added the ls output to show I was in the correct directory.
EDIT 10/8/21 v2:
I used the following command and did not receive an error.
g++ randomCodeWhileReading.cpp -o main -std=c++20
Now just confused where the output went. By #nate's responses I assume it was sent to main? Just wanted to see a cout using std::numbers::pi
EDIT 10/8/21 v3:
All clear nate explained program can be ran by using ./main
EDIT 10/8/21 v4:
... I repeated the earlier command and got a error:
g++ randomCodeWhileReading.cpp -o main -std=c++20
cc1plus: fatal error: randomCodeWhileReading.cpp: No such file or directory
compilation terminated.
can someone explain what went wrong this time? (I am still in the same directory). After using ls it seems that the file is no longer in the directory seems to be deleted?
EDIT 10/8/21 v5:
I think the file got deleted when I was explaining the error to a friend and the wrong ways I was running the command lol. All good :D !
You need to compile with the extra flag -std=c++20.
Moreover, there is an error in your code: pi and pi2 are declared const, hence you cannot modify them after they are initialized. Use this instead:
#include <iostream>
#include <numbers>
int main()
{
const long double pi = std::numbers::pi_v<long double>;
const long double pi2 = std::numbers::pi_v<long double>;
std::cout << pi << std::endl << pi2;
}
Please try this code and this "compile" command on your machine with your version of g++:
/*
* TEST ENVIRONMENT: MSYS2 (Windows 10)
* COMPILER:
* g++ --version
* g++.exe (Rev5, Built by MSYS2 project) 10.3.0
* BUILD COMMAND:
* g++ -g -Wall -pedantic -std=c++2a -o x x.cpp
* <= NOTE: the correct command for C++ 20 compatibility in g++ 10.x is "-std=c++2a"
* RUN COMMAND:
* ./x
* 2pi=6.28319
*/
#include <iostream>
#include <numbers>
int main()
{
auto two_pi = 2*std::numbers::pi;
std::cout << "2pi=" << two_pi << '\n';
}
If it works, great. If it's the same, try "-std=c++20" and/or "-std=gnu++20". Look here for details: https://gcc.gnu.org/projects/cxx-status.html
See also:
https://stackoverflow.com/a/67453352/421195
https://stackoverflow.com/a/67406788/421195
Definitely "Update" your post to report back what happens. Be sure to copy/paste your commands and any error messages EXACTLY.
'Hope that helps.

Trivial Eigen3 Tensor program does not build without -On

I'm trying to build a write of software with the Tensor module provided as unsupported from eigen3. I've written a simple piece of code that will build with a simple application of VectorXd (just printing it to stdout), and will also build with an analogous application of Tensor in place of the VectorXd, but WILL NOT build when I do not throw an optimization flag (-On). Note that my build is from within a conda enviromnent that is using conda-forge compilers, so the g++ in what follows is the g++ obtained from conda forge for ubuntu. It says its name in the error messages following, if that is perceived to be the issue.
I have a feeling this is not about the program I'm trying to write, but just in case I've included an mwe.cpp that seems to produce the error. The code follows:
#include <eigen3/Eigen/Dense>
#include <eigen3/unsupported/Eigen/CXX11/Tensor>
#include <iostream>
using namespace Eigen;
using namespace std;
int main(int argc, char const *argv[])
{
VectorXd v(6);
v << 1, 2, 3, 4, 5, 6;
cout << v.cwiseSqrt() << "\n";
Tensor<double, 1> t(6);
for (auto i=0; i<v.size(); i++){
t(i) = v(i);
}
cout << "\n";
for (auto i=0; i<t.size(); i++){
cout << t(i) << " ";
}
cout << "\n";
return 0;
}
If the above code is compiled without any optimizations, like:
g++ -I ~/miniconda3/envs/myenv/include/ mwe.cpp -o mwe
I get the following compiler error:
/home/myname/miniconda3/envs/myenv/bin/../lib/gcc/x86_64-conda_cos6-linux-gnu/7.3.0/../../../../x86_64-conda_cos6-linux-gnu/bin/ld: /tmp/cc2q8gj4.o: in function `Eigen::internal::(anonymous namespace)::get_random_seed()':
mwe.cpp:(.text+0x15): undefined reference to `clock_gettime'
collect2: error: ld returned 1 exit status
If instead I ask for 'n' optimization level, like the following:
g++ -I ~/miniconda3/envs/loos/include/ -On mwe.cpp -o mwe
The program builds without complaint and I get expected output:
$ ./mwe
1
1.41421
1.73205
2
2.23607
2.44949
1 2 3 4 5 6
I have no clue why this little program, or the real program I'm trying to write, would be trying to get a random seed for anything. Any advice would be appreciated. The reason why I would like to build without optimization is so that debugging is easier. I actually thought all this was being caused by debug flags, but I realized that my build tool's debug setting didn't ask for optimization and narrowed that down to the apparent cause. If I throw -g -O1 I do not see the error.
Obviously, if one were to comment out all the code that has to do with the Tensor module, that is everthing in main above 'return' and below the cwiseSqrt() line, and also the include statement, the code builds and produces expected output.
Technically, this is a linker error (g++ calls the compiler as well as the linker, depending on the command line arguments). And you get linker-errors if an externally defined function is called from somewhere, even if the code is never reached.
When compiling with optimizations enabled, g++ will optimize away uncalled functions (outside the global namespace), thus you get no linker errors. You may want to try -Og instead of -O1 for better debugging experience.
The following code should produce similar behavior:
int foo(); // externally defined
namespace { // anonymous namespace
// defined inside this module, but never called
int bar() {
return foo();
}
}
int main() {
// if you un-comment this line, the
// optimized version will fail as well:
// ::bar();
}
According to man clock_gettime you need to link with -lrt if your glibc version is older than 2.17 -- maybe that is the case for your setup:
g++ -I ~/miniconda3/envs/myenv/include/ mwe.cpp -o mwe -lrt

Code::blocks, SIGSEGV, Segmentation fault. In? ()

I have to debug a segfault in my C++ program using Code::Blocks.
Unfortunately, the stack trace isn't showing correctly, instead I see ?? ()
Here is a minimal example:
#include <iostream>
using namespace std;
int main()
{
int *plop;
cout << *plop << endl;
return 0;
}
The debugger says:
Program received signal SIGSEGV, Segmentation fault. In ?? () ()
But I was expecting something more useful like "In main ()"
EDIT: here is the build log, if it helps
-------------- Build: Debug in tests (compiler: GNU GCC Compiler)---------------
g++.exe -Wall -fexceptions -g -O -pedantic -Wextra -std=c++0x -std=c++14 -c D:\C\tests\main.cpp -o obj\Debug\main.o
D:\C\tests\main.cpp: In function 'int main()':
D:\C\tests\main.cpp:8:14: warning: 'plop' is used uninitialized in this function [-Wuninitialized]
cout << *plop << endl;
^
g++.exe -o bin\tests.exe obj\Debug\main.o -s
Output file is bin\tests.exe with size 542.00 KB
2nd EDIT: finally solved :)
For those who came here by google : strip symbols -s and Optimizer -O compiler options were checked in my case, theses options conflicts with -g as they removes debug symbols in compiled code.
Thanks for everyone for answering
you must initialize the int *plop; pointer like bellow, then print the value :
#include <iostream>
using namespace std;
int main()
{
int *plop = new int(15);
// *plop = 120; // you can change the plop value as custom
cout << *plop << endl;
return 0;
}
result will be : 15
You are dereferencing an uninitialized pointer. That's undefined behaviour and your program is meaningless.
The compiler is free to generate whatever it pleases (including code causing a segfault or not doing anything at all) - basically, all bets are off and you can trust nothing and you can't even count on your debugger showing you anything sane since it just has to work with what the compiler generated - which could be whatever.
Don't work with uninitialized variables / invoke UB.

Enable multithreading Eclipse C++

I have been trying to get a program working in Eclipse C++. One of the functions uses multithreading from std. Here is the function in the code:
void PrimeCheck::checkFull(long long int number)
{
std::thread t1(&PrimeCheck::checkFirstHalf, this, number);
std::thread t2(&PrimeCheck::checkSecondHalf, this, number);
t1.join();
t2.join();
}
When searching for a solution, I came across many solutions, all of which stating to either add a -pthread flag or a -std=c++11 in addition to changing the dialect to C++11. All of which I have done. This is what the compile command looks like in eclipse so you can see exactly which modifications I have already added:
Building file: ../src/Prime Checker.cpp
Invoking: GCC C++ Compiler
g++ -std=c++0x -D__GXX_EXPERIMENTAL_CXX0X__ -O2 -g -Wall -c -fmessage-length=0 -std=c++11 -pthread -Wl,--whole-archive -lpthread -Wl,--no-whole-archive -MMD -MP -MF"src/Prime Checker.d" -MT"src/Prime\ Checker.d" -o "src/Prime Checker.o" "../src/Prime Checker.cpp"
Finished building: ../src/Prime Checker.cpp
And this is the linker command as it appears in eclipse:
Invoking: GCC C++ Linker
g++ -Wl,--no-as-needed -pthread -shared -o [A bunch of .o files]
The code compiles correctly, and eclipse content assist recognizes thread as a member of std. Yet, when I run the program I still this error:
terminate called after throwing an instance of 'std::system_error'
what(): Enable multithreading to use std::thread: Operation not permitted
To test this, I wrote a simple program outside of Eclipse which looked like this:
#include <thread>
#include <iostream>
using namespace std;
void func1(int x){
for(int i=0; i<x; i++){
cout << " " << 1 + i;
}
}
void func2(){
for(int j=0; j<5; j++){
cout << "Standard message! ";
}
}
int main(){
int input;
cout << "Give me a number:" << endl;
cin >> input;
thread t1(func1, input);
thread t2(func2);
t1.join();
t2.join();
return 0;
}
And compiled it in the terminal with this:
g++ ThreadTest.cpp -o Program.o -std=c++11 -pthread
And the program ran without error. I think this means that there's something wrong with Eclipse, but I'm not sure.
As a note, I'm doing this on Ubuntu 14.04 with gcc version 4.8.4. Also, I know that similar questions have been asked, but as far as I can tell, I've implemented those solutions with little success.
Help would be appreciated. Thanks!
Solved. Using Eclipse IDE for C/C++ Developers v4.7.3a in Ubuntu 14.04.
1/2. Problem description
Just trying to run this sample code:
mutex.cpp:
// mutex example
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex
std::mutex mtx; // mutex for critical section
void print_block (int n, char c) {
// critical section (exclusive access to std::cout signaled by locking mtx):
mtx.lock();
for (int i=0; i<n; ++i) { std::cout << c; }
std::cout << '\n';
mtx.unlock();
}
int main ()
{
std::thread th1 (print_block,50,'*');
std::thread th2 (print_block,50,'$');
th1.join();
th2.join();
return 0;
}
From: http://www.cplusplus.com/reference/mutex/mutex/
It builds and runs just fine on the command line with the following command, but will not run in Eclipse!
Command-line command that builds and runs in a terminal just fine:
g++ -Wall -std=c++11 -save-temps=obj mutex.cpp -o ./bin/mutex -pthread && ./bin/mutex
Eclipse error when I try to run it in Eclipse:
terminate called after throwing an instance of 'std::system_error'
what(): Enable multithreading to use std::thread: Operation not permitted
2/2. The solution to make it build and run in Eclipse is as follows:
A. Enable pthread for compiler:
Project --> Properties --> C/C++ Build --> Settings --> GCC C++ Compiler --> Miscellaneious --> type in -std=c++11 to the "Other flags" box, and check the box for "Support for pthread (-pthread)". See yellow highlighting here:
B. Enable pthread for Linker:
Then, withOUT closing this window, also set this setting for the Linker:
in center pane: GCC C++ Linker --> General --> check the box for "Support for pthread (-pthread)", as shown here:
Click "Apply and Close". It will now build and run.

Runtime error for CLang compiled program (Mac) reading double type with std::cin

I'm pretty new to C++ and working through some examples of the book "Programming Principles and Practices Using C++" (2nd Edition). I wrote the following simple Program (in file Main.cpp):
#include <iostream>
#include <string>
int main () {
double d = 0;
std::string s = "";
while (std::cin >> d >> s) {
std::cout << "--" << d << " " << s << "\n";
}
std::cout << "FATAL? "<< d << " " << u << "\n";
}
Compiling the program (on the command line) with CLang (Apple LLVM version 5.1 (clang-503.0.40) (based on LLVM 3.4svn) Target: x86_64-apple-darwin13.2.0 Thread model: posix):
clang++ -o Main -std=c++11 -stdlib=libc++ Main.cpp
works fine without any errors. However, when I run the program it behaves strange. I tested the following input:
123m
which results in
--123 m
which is fine (the same holds for entering 123 m). But, entering the following:
123a
results in:
FATAL? 0 m
The same happens for most other characters (e.g. b, c, ...). Entering 123 a works fine though (output: --123 a).
Using GNU g++ works on the other hand. Further, the problem does not come up on a Linux machine compiling the same program with CLang.
As stated before, I'm new to C++ and this seems to be a Mac OS X specific problem. Is this a bug in the Mac CLang implementation or am I doing something seriously wrong here :(?
Thanks in advance!
Ok, I found a solution to the problem in this question asked: CGAL: How can I successfully compile and link CGAL examples (on Mac OS X 10.9 Mavericks)
Compiling with clang++ as follows:
clang++ -o Main -std=c++11 -stdlib=libstdc++ Main.cpp
instead of:
clang++ -o Main -std=c++11 -stdlib=libc++ Main.cpp
solved the problem.
Anyway, as libc++ should be the preferred library to use with clang++ (as I just was told offline) I think it's time for a bug report.
std::basic_istream::operator>> calls std::num_get::get to extract the value from input. Until C++11, the behaviour of std::num_get::get was like that of scanf with the appropriate formatting string. C++11 onwards, std::num_get::get ends up calling strto* functions, which have a more flexible matching than the one based on scanf. In your example, 123[a-f] get interpreted as hex. Since all the input has been consumed by >>d, the >>s part of while(std::cin >> d >> s) leads to the parse failing.