Weird glibc error with writing out a file - c++

I'm getting a strange error:
*** glibc detected *** findbasis: free(): invalid next size (normal): 0x0000000006a32ce0 ***
When I try to close() a std::ofstream:
void writeEvectors(int l, parameters params, PetscReal* evectors, int basis_size)
{
for (int n = 1 + l; n <= params.nmax(); n++)
{
std::stringstream fname(std::ios::out);
fname << params.getBasisFunctionFolder() << "/evectors_n" << std::setw(4) << std::setfill('0') << n << "_l" << std::setw(3) << std::setfill('0') << l;
std::ofstream out(fname.str().c_str(), std::ios::binary);
std::cerr << "write out file:" << fname.str() << " ...";
out.write((char*)( evectors + n * basis_size),sizeof(PetscReal) * basis_size);
std::cerr << "done1" << std::endl;
if (out.fail() || out.bad())
std::cerr << "bad or fail..." << std::endl;
out.close();
std::cerr << "done2" << std::endl;
}
std::cout << "done writing out all evectors?" << std::endl;
}
When run, this program never reaches the "done2" (or the "bad or fail..."), however the "done1" is reached. Also, the data that is written out is good (as in what I expect).
I'm honestly at a loss as to why this happens, I can't think of any reason "close()" would fail.
Thanks for any help.
(I'm beginning to think it is some sort of compiler bug/error. I'm running GCC 4.1.2 (!) (RHEL 5 I believe) through mpicxx)

The glibc error sounds like there's a problem with freeing memory. If you run inside Valgrind, a free memory profiler, it ought to give you a more helpful explanation of the error.
Running in Valgrind is fairly painless - just compile the executable with the -g option to add debugging flags (assuming you're using the GNU compiler) and then in your Linux terminal enter valgrind ./your_executable and see what happens.

Related

C++ MySQL-connector on Arch-Linux/arm

I have written a program using C++/C, the MySQL C++ connector and ncurses/CDK. It compiles just fine, and runs fine as well on an x86/64 architecture. It crashes, however, when run on a Raspberry Pi B+ (ArchLinux).
I realize this is a pretty hard question to answer, but maybe someone more experienced can help.
Here's the (hopefully) relevant Code:
//Open Connection to the Database
nrpeout::MYSQL_CON localhost("127.0.0.1", 3306, "root", "toor");
//localhost.write_attributes_to_console();
con = localhost.open_database_connection();
//Create a new object of type nrpeoutputquery
nrpeout::Nrpeoutputquery current_query("SELECT * FROM nrpeout", con);
//Execute query
res = current_query.execute_query();
//Close Database Connection
localhost.close_database_connection(con);
} catch (sql::SQLException &e) {
//Handle SQL-Exceptions
std::cout << "# ERR: SQLException in " << __FILE__;
std::cout << "(" << __FUNCTION__ << ") on line "
<< __LINE__ << std::endl;
std::cout << "# ERR: " << e.what();
std::cout << " (MySQL error code: " << e.getErrorCode();
std::cout << ", SQLState: " << e.getSQLState() << " )" << std::endl;
} catch(...) {
//Handle Standard Exceptions
std::cout << "Unknown Exception raised. Please contact your Administrator" << std::endl;
}
nrpeout::NrpeResultSet* currentResults = new nrpeout::NrpeResultSet(res);
Using Valgrind and GDB, I have tried to narrow the error down to the line where I create the object "currentResults".
Here's the member function that saves the query results:
nrpeout::NrpeResultSet::NrpeResultSet(sql::ResultSet* res)
{
for (unsigned int i = 0; i < res->rowsCount(); ++i)
{
res->next();
std::string command = res->getString("command");
//Shorten the String
size_t posCommand = command.find("_");
std::string shortened_command = command.substr(posCommand+1);
int ret = res->getInt("ret");
std::string text = res->getString("text");
//Shorten the Text
size_t posText = text.find("|");
std::string shortened_text = text.substr(0, posText-1);
std::string last_updated = res->getString("last_updated");
this->results.push_back(Row(shortened_command, ret, shortened_text, last_updated));
}
Well, you are not catching an exception, which you may want to handle. InvalidInstanceException is thrown when using closed databse connections, statements or resultsets.
My suggestion is to run your code with a gdb and catch exceptions:
gdb ./some-program
$ catch throw
$ r
This will break after each exception being thrown. (But also includes handled exceptions, so there may be quite a few breaks, depending on how long it takes you to get to the important part.)

Read binary data from a binary file

I am writing a structure into a file using the following line:
std::fstream snif::fileHandler;
fileHandler.write(reinterpret_cast<char*>(rawData), sizeof(rawDataStruct));
where rawdataStruct is:
typedef struct _rawData rawDataStruct;
now after writing the structures into the file, I am reading the structure from the beginning of the binary file using:
std::cout << "going for print data read from file\n";
snif::fileHandler.seekg(0); //, std::ios::beg);
snif::fileHandler.read(reinterpret_cast<char*>(rawData), sizeof(rawDataStruct));
if (snif::fileHandler.fail()) {
std::cerr << "reading error\n";
exit(0);
}
std::cout << "PSH flag = " << rawData->tcpFlag.PSH << std::endl
<< "source port " << rawData->sourcePort << std::endl
<< "destination port " << rawData->destinationPort << std::endl
<< " sequence number " << rawData->sequenceNumber << std::endl
<< " Acknowledge number " << rawData->acknowledgeNumber << std::endl
<< " acknowledge flag " << rawData->tcpFlag.ACK << std::endl
<< " SYN flag " << rawData->tcpFlag.SYN << std::endl
<< "FIN flag " << rawData->tcpFlag.FIN << std::endl;
but if I check my standard output, the last line geting printed is:
"going for print data read from file";
There is no code showing it, but what mode is the file opened? Hopefully it is configured for binary. To see the available options, review std::basic_fstream and std::ios_base::openmode. I suggest to make sure that the following open modes are set:
ios::binary | ios::out | ios::in | ios::trunc
Depending on what purpose is happening, ios::trunc (truncate) may have to be replaced by ios::app (append).
While doing some basic testing, it has been discovered on my C++11 compliant compiler that the
fileHandler.write(reinterpret_cast<char*>(rawData), sizeof(rawDataStruct));
has a potential problem that is easily solved by adding the & operator in front of the rawData like this:
fileHandler.write(reinterpret_cast<char*>(&rawData), sizeof(rawDataStruct));
The compiler should have given a warning, but that is contingent on the compiler version, and whether the -Wall option or better is used. This may explain how the screen output seemingly stops at the
"going for print data read from file"
message. The read function also needs the & operator in front of rawData:
snif::fileHandler.read(reinterpret_cast<char*>(&rawData), sizeof(rawDataStruct));
Perhaps a run-time exception from the reinterpret_cast<> operator is being thrown that is not being caught. It is difficult to know until the system and compiler are documented.
Additionally, if rawData is declared as a pointer, then a better variable name is pRawData, as well as posting more of the code. For example, if the pRawData is never pointing to a valid instance of the rawDataStruct, then unpredictable things will occur.

Eclipse C++ console print order linux

I know there many subjects about this but none of them helps me.
I use in my C/C++ project std::cout and std::cerr to print info (cout) or error (cerr).
But when executing it they don't print in the right order, they seems to "group print". Sometime all cerr then all cout and sometime all cout first then all cerr.
I tried to flush() after every line, don't work. (luckily, it would be awful having to use it every time ...).
Also tried setvbuf(stdout, NULL, _IONBF, 0); same issue...
If run program directly in linux's console, order is good but eclipse console more useful due to colors.
Here code sample
#include <iostream>
int main(int argc, char** argv)
{
std::cerr << __LINE__ << std::endl;
std::cerr << __LINE__ << std::endl;
std::cout << __LINE__ << std::endl;
std::cerr << __LINE__ << std::endl;
std::cerr << __LINE__ << std::endl;
std::cout << __LINE__ << std::endl;
}
And console print
11
12
14
15
13
16
==> Wrong order ...
In this example cerr comes out before cout
Ok the situation is as follows, std::cout is added into a buffor, and std::cerr does not. std::cerr is faster and it does not need to be flushed. Also std::cerr and std::cout uses different streams.
The problem here is that std::cerr shows right away and std:cout needs to be flushed before it's showed.

boost::iostreams::mapped_file_sink throws unknown exception

Could you guys help me decypher unknown exception that is thrown by boost::iostreams::mapped_file_sink ?
My configuration
boost 1.51
Visual Studio 2012 on Windows 7
GCC 4.7 on Ubuntu
Here is the code I have
try
{
boost::iostreams::mapped_file_params params_;
boost::iostreams::mapped_file_sink sink_;
params_.length = 0;
params_.new_file_size = 1024;
params_.path = "./test.bin";
sink_.open(params_);
sink_.close();
}
catch (std::ios::failure& ex)
{
std::cout << "\t" << "what: " << ex.what() << "\n";
}
catch (std::system_error& ex)
{
std::cout << "\t" << "code: " << ex.code() << " what: " << ex.what() << "\n";
}
catch (std::runtime_error& ex)
{
std::cout << "\t" << ex.what() << "\n";
}
catch (boost::archive::archive_exception& ex)
{
std::cout << "\t" << ex.what() << "\n";
}
catch (boost::exception& ex)
{
std::cout << "blah\n";
}
catch (std::exception& ex)
{
std::cout << "\t" << ex.what() << " --- " << typeid(ex).name() << "\n";
}
It always works in Windows.
In Ubuntu it creates empty file of given size but throws exception on open(). Subsequent execution of the code if exists doesn't cause exception.
The worst part is that I can't see the reason of the exception. I can only catch std::exception whose what() returns meaningless "std::exception".
In desperate attempt to find out what's wrong I output typeid(ex).name() which shows
N5boost16exception_detail10clone_implINS0_19error_info_injectorISt9exception
which according to Google means: boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<std::exception> >
Any ideas what's wrong?
You could run the code in a debugger and set a breakpoint in the function which actually throws an exceptions, e.g., __cxa_throw. The name of the function may be different on your system: use nm -po program | less and search for a function containing throw. Set a breakpoint in the one(s) which look most likely as if they are created by the system. If there are only few exceptions being thrown, you can also set a breakpoint into std::exception::exception().
After 50 mins of guessing I found out that problem was in length field. The documentation doesn't say that but its default value has to be -1 as stated in source code
BOOST_STATIC_CONSTANT(size_type, max_length = static_cast<size_type>(-1));
I intuitively assumed that if I set new_file_size to be more than zero it would ignore length.

Simple console program will not exit if cudaMalloc is called

The following simple program never exits if the cudaMalloc call is executed. Commenting out just the cudaMalloc causes it to exit normally.
#include <iostream>
using std::cout;
using std::cin;
#include "cuda.h"
#include "cutil_inline.h"
void PrintCudaVersion(int version, const char *name)
{
int versionMaj = version / 1000;
int versionMin = (version - (versionMaj * 1000)) / 10;
cout << "CUDA " << name << " version: " << versionMaj << "." << versionMin << "\n";
}
void ReportCudaVersions()
{
int version = 0;
cudaDriverGetVersion(&version);
PrintCudaVersion(version, "Driver");
cudaRuntimeGetVersion(&version);
PrintCudaVersion(version, "Runtime");
}
int main(int argc, char **argv)
{
//CUresult r = cuInit(0); << These two lines were in original post
//cout << "Init result: " << r << "\n"; << but have no effect on the problem
ReportCudaVersions();
void *ptr = NULL;
cudaError_t err = cudaSuccess;
err = cudaMalloc(&ptr, 1024*1024);
cout << "cudaMalloc returned: " << err << " ptr: " << ptr << "\n";
err = cudaFree(ptr);
cout << "cudaFree returned: " << err << "\n";
return(0);
}
This is running on Windows 7, CUDA 4.1 driver, CUDA 3.2 runtime. I've trace the return from main through the CRT to ExitProcess(), from which it never returns (as expected) but the process never ends either. From VS2008 I can stop debugging OK. From the command line, I must kill the console window.
Program output:
Init result: 0
CUDA Driver version: 4.1
CUDA Runtime version: 3.2
cudaMalloc returned: 0 ptr: 00210000
cudaFree returned: 0
I tried making the allocation amount so large that cudaMalloc would fail. It did and reported an error, but the program still would not exit. So it apparently has to do with merely calling cudaMalloc, not the existence of allocated memory.
Any ideas as to what is going on here?
EDIT: I was wrong in the second sentence - I have to eliminate both the cudaMalloc and the cudaFree to get the program to exit. Leaving either one in causes the hang up.
EDIT: Although there are many references to the fact that CUDA driver versions are backward compatible, this problem went away when I reverted the driver to V3.2.
It seems like you're mixing the driver API (cuInit) with the runtime API (cudaMalloc).
I don't know if anything funny happens (or should happen) behind the scenes, but one thing you could try is to remove the cuInit and see what happens.