C++ STL 容器中的 NULL 指针

发布于 2024-08-18 02:35:38 字数 460 浏览 4 评论 0原文

不幸的是,我并没有完全开发自己开发的程序。 我最近注意到 unordered_set 的运算符 -- 上出现 Visual Studio 致命错误,该错误是通过简单插入指向 unordered_set 的指针而调用的。在查看了当地人之后,我注意到 set 只有 2 个元素,最后一个为 NULL (所以我想这就是它崩溃的原因)。现在的问题是:(理论上)unordered_set(或任何其他 STL 容器)如何获取 NULL 指针作为其元素之一。程序是多线程的,但根据我的评论,这部分代码应该只能从一个线程访问。谢谢。

有兴趣的人可以查看调用堆栈和部分源代码: http://privatepaste.com/c8e7f35a4e (PushToProcessed是从Object本身调用的,它传递对自身的引用,所以不能为 NULL)

I am, unfortunately, not working on a program developed by myself fully.
I recently I noticed a Visual Studio Fatal Error on operator-- of unordered_set, which was called from simple insertion of a pointer to unordered_set. After reviewing the locals, I've noticed that set only has 2 elements last of which is NULL (so I suppose that's what it crashed on). Now to the question: How (theoretically) can an unordered_set (or any other STL container) get a NULL pointer as one of its elements. Program is multi-threaded, but according to my reviews, that part of code should only be accessed from one thread. Thanks.

Call stack and parts of source code for those who are interested:
http://privatepaste.com/c8e7f35a4e (PushToProcessed is called from Object itself, it passes reference to itself, so cannot be NULL)

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

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

发布评论

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

评论(3

梦毁影碎の 2024-08-25 02:35:38

集合可以包含可以为 NULL 的指针。

#include <iostream>
#include <vector>

int main () {
    std::vector<int *> foo;
    foo.push_back (NULL);
    std::cout << foo.size () << std::endl;
    return 0;
}

容器可以轻松包含 NULL 值。您是在谈论容器的内部结构变得混乱吗?

Sets can contain pointers which can be NULL.

#include <iostream>
#include <vector>

int main () {
    std::vector<int *> foo;
    foo.push_back (NULL);
    std::cout << foo.size () << std::endl;
    return 0;
}

A container can easily contain a NULL value. Are you talking about the internals of a container getting messed up?

画骨成沙 2024-08-25 02:35:38

NULL 是完全有效的指针值。如果传入 NULL,它将像任何内存地址一样被处理。由于您只看到 2 个条目,我敢打赌您真正看到的是许多 NULL 指针被“添加”到您的集合中,但由于它是一个集合,因此仅保留一个副本。

编辑:

为了测试我的假设,即许多项目被添加为所有 NULL 值,为什么不对 cout 进行简单的调用,说明“添加了地址 = 的新项目”指针的值。打赌你会感到惊讶。

a NULL is a perfectly valid pointer value. If a NULL is passed in, it will be treated just like any memory address. Since you're seeing only 2 entries I would wager a guess that what you really are seeing is many NULL pointers being "added" to your set but since it is a set only one copy retained.

Edit:

To test my hypothesis of many items being added all of NULL value why not put in a simple call to cout stating "New item added with address = " the value of the pointer. Bet you'll be surprised.

旧夏天 2024-08-25 02:35:38

我相信容器指针值可以通过取消引用的非常量迭代器来设置,如 (*iter) = NULL。这当然会糟糕

I believe a container pointer value can be set via a dereferenced non-const iterator as in (*iter) = NULL. This of course would be bad.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文