【发布时间】:2022-01-04 16:41:49
【问题描述】:
类似于LeetCode C++ Convert char[] to string, throws AddressSanitizer: stack-buffer-overflow error
代码是
#include <string>
int main() {
char buf[10] = {6, 6, 6, 6, 6, 6, 6, 6, 6, 6};
std::string s{buf, 2, 3};
return 0;
}
执行结果是地址清理程序抱怨strlen 的stack-buffer-overflow:
$ clang++ -g -fsanitize=address foo.cpp ; ./a.out
=================================================================
==1001715==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7ffd76b2510a at pc 0x00000042f029 bp 0x7ffd76b250b0 sp 0x7ffd76b24870
READ of size 23 at 0x7ffd76b2510a thread T0
#0 0x42f028 in strlen (/tmp/a.out+0x42f028)
#1 0x7fd6de786e9b in std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&) (/usr/lib/x86_64-linux-gnu/libstdc++.so.6+0x145e9b)
#2 0x4c6cfe in main /tmp/foo.cpp:6:19
#3 0x7fd6de2d60b2 in __libc_start_main /build/glibc-eX1tMB/glibc-2.31/csu/../csu/libc-start.c:308:16
#4 0x41c3fd in _start (/tmp/a.out+0x41c3fd)
我希望std::string s{buf, 2, 3}; 调用具有已知边界的构造函数重载(从 2 开始,长度为 3)。为什么叫strlen()?使用了哪个重载?
【问题讨论】:
标签: c++ arrays string strlen address-sanitizer