检测到堆损坏,堆缓冲区结束后仍在写内存

发布于 2025-01-22 01:12:43 字数 419 浏览 0 评论 0原文

因此,我正在做有关课程和其他作业的作业。一切都编译了,我得到了预期的输出,但是我一直遇到一个错误,说 “检测到的堆损坏..... CRT检测到了堆在堆缓冲区结束后写下内存。”

当我在此之后返回代码时,一行被绿色突出显示,并说“在写信给所有者时,缓冲区超支”

这是代码:

void bank::setOwner(const char* nameOwner) 
{
    if (owner != nullptr)
        delete[] owner;
    int i = 0;
    while (nameOwner[i++] != '\0');
    owner = new char[i];
    while (i >= 0) {
        owner[i--] = nameOwner[i];
    }
}

So I am doing this assignment about classes and whatnot. Everything compiles and i get the expected output, but I keep getting an error that says
"HEAP CORRUPTION DETECTED..... CRT detected that the application wrote memory after the end of heap buffer."

When I go back into my code after this, one line is highlighted by green and says "Buffer overrun while writing to owner"

Here is the code:

void bank::setOwner(const char* nameOwner) 
{
    if (owner != nullptr)
        delete[] owner;
    int i = 0;
    while (nameOwner[i++] != '\0');
    owner = new char[i];
    while (i >= 0) {
        owner[i--] = nameOwner[i];
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迷荒 2025-01-29 01:12:43

让我介绍大 rubber ducky ducky

现在进行了介绍,您可以使用其无限智慧来帮助检测问题和越野车代码。对话可能会这样:

您:

橡皮鸭,如果说,i是10?

,第7至9行中会发生什么

rd:

好吧,一个名为所有者的10个字符的阵列将在第7行中分配,然后在第9行中,在第一个迭代中,您将在lonts [10 ],那就是只能占10个元素的数组中的索引11。

you:

这是不好的吗?

rd:

是的,您将在数组范围之外写作。这意味着您可以在可能不属于程序的内存中写作,即使这样做,它也会导致我们称之为不确定的行为,这绝对是非常糟糕的。

我注意到您在代码中使用原始指针,这是否需要?您能想到您可以使用的其他工具吗?

您:

我肯定可以使用std :: String

  // std ::字符串所有者;

void bank :: setOwner(const std :: string& newmowner) 
{
   所有者=命名者;
}
 

Let me introduce to the great rubber ducky.

Now that introductions are made, you can use its infinite wisdom to help detect problems and buggy code. The conversation could go like this:

You:

Rubber ducky, what will happpen in the lines 7 through 9 if, let's say, i is 10?

RD:

Well, an array of 10 chars named owner will be allocated in line 7, then in line 9, in the very first iteration you will be writing in owner[10], that is index 11 in an array that can only take 10 elements.

You:

Is that bad?

RD:

Yes, you will be writing outside the bounds of the array. That means you can be writing in memory that may not belong to your program, and even if it does, it will lead to something we call undefined behavior, and that's definitely very bad.

I noticed you are using raw pointers in your code, is that needed? Can you think of other tools you could use that would make more sense here?

You:

I could surely use std::string:

//std::string owner;

void bank::setOwner(const std::string& nameOwner) 
{
   owner = nameOwner;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文