public inbox for gcc-help@gcc.gnu.org
 help / color / mirror / Atom feed
* std::string clobbers memory when compiling without optimizations
@ 2014-10-03  8:19 Henrik Mannerström
  2014-10-03  9:58 ` Jonathan Wakely
  0 siblings, 1 reply; 7+ messages in thread
From: Henrik Mannerström @ 2014-10-03  8:19 UTC (permalink / raw)
  To: gcc-help

Hello,

I found a program that produces incorrect behavior when compiling with
-Og or without optimization. By running gdb I can pinpoint the problem
to the std::string constructor, but I have to do more research to be
able to step through that with gdb. My minimal working example is not so
minimal, but I have not been able to reproduce the problem with a
smaller program. The Eigen library used is from eigen.tuxfamily.org . On
the line indicated by "Correct output" the program prints what I expect,
two lines later, the contents has changed. With gdb I can see that the
memory content is changed by the std::string namestring(name) line in
the t2s function. Watching the memory location that is changed gives 
std::basic_string<char, std::char_traits<char>, std::allocator<char>
>::basic_string(char const*, std::allocator<char> const&)  as the
offending location. Compiling with  g++-4.9 -std=c++11  gives the error,
but adding -O1 produces correct results.

Do you have any suggestions on what to do next?

BR,
Henrik Mannerström




#include <cxxabi.h>
#include <string>
#include <typeinfo>
#include <cstdlib>

template <typename T>
std::string t2s(T tt) {
  char *name;
  int status;
  name = abi::__cxa_demangle(typeid(tt).name(), 0, 0, &status);
  std::string namestring(name); // Variable Sigma from main is changed
at this line.
  std::free(name);
  return namestring;
}

#include <Eigen/Core>
#include <iostream>

int main() {
  typedef Eigen::Matrix<double, 1, 3> cVector;

  const cVector mean = (cVector() << 1, 2, 3).finished();
  const auto Sigma = (cVector() << 1, 1, 1).finished().asDiagonal();

  std::cout << "Correct diagonal: " << Sigma.diagonal() << std::endl; //
Correct output: 1 1 1

  std::cout << t2s(mean) << std::endl;

  std::cout << "Incorrect diagonal: " << Sigma.diagonal() << std::endl;
// Incorrect output: [random double] 1 1
}

^ permalink raw reply	[flat|nested] 7+ messages in thread

end of thread, other threads:[~2014-10-03 12:36 UTC | newest]

Thread overview: 7+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2014-10-03  8:19 std::string clobbers memory when compiling without optimizations Henrik Mannerström
2014-10-03  9:58 ` Jonathan Wakely
2014-10-03 10:09   ` Henrik Mannerström
2014-10-03 10:20     ` Jonathan Wakely
2014-10-03 10:31       ` Henrik Mannerström
2014-10-03 12:36         ` Jonathan Wakely
2014-10-03 10:31       ` Marc Glisse

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).