在 leetcode 上提交解决方案时出现堆栈缓冲区溢出错误

Stack buffer overflow error while submitting solution on leetcode

本文关键字:堆栈 缓冲区 溢出 错误 leetcode 提交 解决方案      更新时间:2023-10-16

我正在尝试在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);
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来查看任何问题,但它也说没有问题,因为您可以看到输出。

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)

所以我的问题是潜在的错误是什么? 我的代码中是否有问题损坏还是什么?答案将不胜感激。谢谢。

我猜你正在尝试用恒定的记忆来解决。不过,您可以使用记忆来解决此问题,编码/调试要简单得多。

这将通过:

#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;
}
};
<小时 />

参考资料

  • 有关其他详细信息,您可以查看讨论区。有很多公认的解决方案,包括多种语言和解释、高效的算法以及渐近时空复杂性分析1、2