C++ 在leetcode上提交解决方案时发生堆栈缓冲区溢出错误
我试图在leetcode上提交我的解决方案,当我提交它时,它会给我一个运行时错误C++ 在leetcode上提交解决方案时发生堆栈缓冲区溢出错误,c++,c++17,C++,C++17,我试图在leetcode上提交我的解决方案,当我提交它时,它会给我一个运行时错误 AddressSanitizer: stack-buffer-overflow on address 0x7ffd6484f411 at pc 0x000000386795 bp 0x7ffd6484ed70 sp 0x7ffd6484ed68 这是我的密码: int lengthOfLongestSubstring(std::string s) { auto start = std::begin(s)
AddressSanitizer: stack-buffer-overflow on address 0x7ffd6484f411 at pc 0x000000386795 bp 0x7ffd6484ed70 sp 0x7ffd6484ed68
这是我的密码:
int lengthOfLongestSubstring(std::string s)
{
auto start = std::begin(s);
std::string substring = std::string(std::begin(s), std::begin(s) + 1);
std::string pre_string = std::string(std::begin(s), std::begin(s) + 1);
for (auto itr = std::begin(s) + 1; itr != std::end(s); ++itr)
{
auto next = itr;
if (std::find(std::begin(substring), std::end(substring), *itr) ==
std::end(substring))
{
substring = std::string(start, itr + 1);
}
else
{
if (++next != std::end(s))
{
start = itr;
pre_string = substring;
substring = std::string(itr, ++itr);
}
}
}
if (pre_string.length() > substring.length())
{
return pre_string.length();
}
else
return substring.length();
}
当我尝试在我的机器上运行它时,它不会给我任何警告。一切都很好。
我正在使用以下命令。
g++-Wall-Wpedantic longestString.cpp-o long.o
此外,我还使用了valgrind
来查看any problem,但它也表示没有问题,因为您可以看到输出
username@droozal:~/leetcode$ valgrind ./long.o
==9473== Memcheck, a memory error detector
==9473== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==9473== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==9473== Command: ./long.o
==9473==
5
==9473==
==9473== HEAP SUMMARY:
==9473== in use at exit: 0 bytes in 0 blocks
==9473== total heap usage: 2 allocs, 2 frees, 73,728 bytes allocated
==9473==
==9473== All heap blocks were freed -- no leaks are possible
==9473==
==9473== For counts of detected and suppressed errors, rerun with: -v
==9473== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
所以我的问题是潜在的错误是什么?我的代码有什么问题吗?如有答复,将不胜感激。谢谢。我想你是想用恒定内存来解。不过,对于这个问题,您可以使用memonization,编码/调试要简单得多 这将通过:
#include <string>
#include <map>
#include <algorithm>
class Solution {
public:
static inline int lengthOfLongestSubstring(const std::string s) {
map<char, int> char_map;
int start = -1;
int longest = 0;
const int length = s.size();
for (int index = 0; index < length; index++) {
if (char_map.count(s[index]) != 0) {
start = std::max(start, char_map[s[index]]);
}
char_map[s[index]] = index;
longest = std::max(longest, index - start);
}
return longest;
}
};
#包括
#包括
#包括。这里有很多公认的解决方案,有各种解释和解释,有高效的算法,还有渐近/复杂性分析
测试数据在哪里?如果s
为空怎么办?顺便说一句,STL是标准库,而std::string
不是STL的一部分。@MohsanAli函数参数的求值顺序未指定。不要执行std::string(itr,++itr)
。(我怀疑它甚至有未定义的行为。)