C++ - Check if pointer is pointing to valid memory (Can't use NULL checks here)

后端 未结 6 1403
名媛妹妹
名媛妹妹 2020-12-21 18:01

I am creating scripting language. When I allocate thing ,it\'s allocate the thing and returns the address and then I do whatever with it and then delete it. I can\'t contro

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-21 18:55

    This is a really bad idea. Whether a pointer is safe to use is based on more than just the value of the pointer, it's based on the entire history of the pointer. For instance, let's say that you allocate some memory, then deallocate it but you keep the pointer to it. This pointer is now invalid. Now something else gets allocated to the memory where the previous pointer is. Now if you try to detect if the old pointer is valid, it appears that it is, because the memory it points to is allocated, but if you try to use it, you get undefined behavior. If you read from it, you'll get garbage. If you try to write to it you'll probably corrupt the heap.

    If all you want to do is detect is whether your process can access the memory that the pointer points to, that is possible but not portable, and definitely not a good idea (it will also be very slow). You basically have try to read from or write to it, and then catch the OS exception or signal that results. As I said, even this is a really bad idea. All it tells you is whether the OS will kill your process if you try to access it; not whether it's actually safe to use.

    For more on why this is a bad idea, check out these blog posts from Raymond Chen, who works on some low-level stuff Windows stuff:

    IsBadXxxPtr should really be called CrashProgramRandomly

    There's no point improving the implementation of a bad idea

提交回复
热议问题