4

The following codes will crash when they are compiled by clang UBSAN

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>

template<class T>
inline std::string floatToString(T i){
    printf("in floatToString\n");
    std::stringstream ss;
    ss.precision(6);
    ss << std::noshowpoint << i;
    printf("exit floatToString\n");
    return ss.str();
}

int main() {
 std::cout << floatToString(1.0) << "\n";
 return 0;
}

Compile with Clang 3.6:

$> clang++-3.6 -fsanitize=undefined -fno-sanitize=float-divide-by-zero,vptr,function -fno-sanitize-recover -o test test.cpp

Then the program crashed:

$> ./test in floatToString /usr/bin/../lib/gcc/x86_64-linux-gnu/4.8/../../../../include/c++/4.8/bits/ios_base.h:96:24: runtime error: load of value 4294966271, which is not a valid value for type 'std::_Ios_Fmtflags'

Can someone help why this problem happens when I turn on clang UBSAN?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
zhanxw
  • 3,159
  • 3
  • 34
  • 32

1 Answers1

1

It's a bug in libstdc++ according to http://lists.cs.uiuc.edu/pipermail/cfe-dev/2013-January/027401.html.

Still present in libstdc++ 5.1.

libc++ works as expected:

$ clang++ -stdlib=libc++ -fsanitize=undefined -fno-sanitize=float-divide-by-zero,vptr,function -fno-sanitize-recover -o test test.cpp -lc++abi

$ ./test
in floatToString
exit floatToString
1
Thomas
  • 3,074
  • 1
  • 25
  • 39
  • @zhanxw: I am still getting "runtime errors": `/usr/lib64/gcc/x86_64-unknown-linux-gnu/5.2.0/../../../../include/c++/5.2.0/bits/ios_base.h:102:24: runtime error: load of value 4294966271, which is not a valid value for type 'std::_Ios_Fmtflags'` – Thomas Aug 10 '15 at 17:10
  • Did you use libc++ and encounter the error? I tried your solution and it worked when used libc++ instead of libstdc++. – zhanxw Aug 11 '15 at 17:45
  • @zhanxw: No, your "works now" made me think it has been fixed in libstdc++ :-). – Thomas Aug 12 '15 at 17:23
  • Got it. I should have said "your solution works" instead "this works". Thanks for the follow up. – zhanxw Aug 13 '15 at 17:23