[英]C++ works fine at my computer but gets address sanitizer heap-buffer-overflow errors on leetcode
I was trying to solve leetcode problem "929. Unique Email Addresses", the code works fine at my computer on Visual Studio Code but when I pasted it on the leetcode, I got address sanitizer heap-buffer-overflow error. 我试图解决leetcode问题“929.独特的电子邮件地址”,代码在我的计算机上运行在Visual Studio Code上正常但是当我将它粘贴在leetcode上时,我得到了地址清理程序堆缓冲区溢出错误。 The code is shown below:
代码如下所示:
class Solution {
public:
int numUniqueEmails(vector<string>& emails) {
string::iterator it;
for (int i = 0; i < emails.size(); i++) {
for (it = emails[i].begin(); *it != '@'; it++) {
if (*it == '.') {
emails[i].erase(it);
it--;
}
if (*it == '+') {
while (*it != '@') {
emails[i].erase(it);
}
break;
}
}
sort(emails.begin(), emails.end());
for (int j = 0; j < emails.size(); j++) {
if (emails[j] == emails[j + 1]) {
emails.erase(emails.begin() + j);
j--;
}
}
}
return emails.size();
}
};
Can someone let me know why the error occurs? 有人能让我知道错误发生的原因吗?
Because the following loops: 因为以下循环:
for (it = emails[i].begin(); *it != '@'; it++)
...
and 和
while (*it != '@')
...
iterate with it
over the string without never ever verifying if the end of the string was reached. 在字符串上迭代
it
,从不验证字符串的结尾是否到达。 If you have a single ill-formatted email address in the input data, you therefore go out of bounds. 如果您在输入数据中有一个格式错误的电子邮件地址,那么您就会超出范围。 So UB.
所以UB。
In addition, you also go out of bounds here: 另外,你也在这里出界:
for (int j = 0; j < emails.size(); j++) {
if (emails[j] == emails[j + 1]) { // what when j == size-1 ????
Finally a potentially nasty issue as well (but could affect the result): your first for
loop should end before the sort()
. 最后一个潜在的讨厌问题(但可能影响结果):你的第一个
for
循环应该在sort()
之前结束。 Why? 为什么? because with some bad luck, the sorting will change the order of the elements, causing an unprocessed address to move before the current i index and thus remain unprocessed.
因为运气不好,排序会改变元素的顺序,导致未处理的地址在当前i索引之前移动,从而保持未处理状态。
Demo with some additional display of intermediary results and some extreme cases. 演示与一些额外的中间结果显示和一些极端情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.