中未初始化的内存块

中未初始化的内存块

本文介绍了VC ++中未初始化的内存块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

众所周知,运行时标记未初始化或刚刚释放的内存块具有特殊的非零标记。有没有办法完全禁用此行为,而不手动将所有未初始化的内存设置为零?因为 0xFEEEFEEE!= 0

As everyone knows, the Visual C++ runtime marks uninitialized or just freed memory blocks with special non-zero markers. Is there any way to disable this behavior entirely without manually setting all uninitialized memory to zeros? It's causing havoc with my valid not null checks, since 0xFEEEFEEE != 0.

Hrm,也许我应该解释一下有点好。我创建和初始化一个变量(通过新),这一切都很好。当我释放它(通过删除),它设置指针 0xFEEEFEEE 而不是 NULL 。当我插入一个适当的检查 NULL ,因为所有好的程序,管理自己的内存应该,我出现的问题, 0xFEEEFEEE 通过 NULL 检查没有问题。有什么好的方法,除了手动设置所有指针 NULL 时删除它们,以检测内存已被释放?我不想使用,因为我不想要开销,虽然它可能是小,因为这是唯一的事情,我会使用Boost for。

Hrm, perhaps I should explain a bit better. I create and initialize a variable (via new), and that all goes just fine. When I free it (via delete), it sets the pointer to 0xFEEEFEEE instead of NULL. When I insert a proper check for NULL, as all good programs that manage their own memory should, I come up with problems as 0xFEEEFEEE passes a NULL check without problems. Is there any good way, other than manually setting all pointers to NULL when deleting them, to detect when memory has already been freed? I would prefer to not use Boost simply because I don't want the overhead, small though it may be, since that's the only thing I'd be using Boost for.

推荐答案

这不是责任 delete 将所有指向对象的指针重置为 NULL
此外,你不应该改变默认的内存填充为Windows DEBUG运行时,你应该使用一些东西像 boost :: shared_ptr<> 任何方式的指针。

It is not the responsibility of delete to reset all the pointers to the object to NULL.Also you shouldn't change the default memory fill for the windows DEBUG runtime and you should use some thing like boost::shared_ptr<> for pointers any way.

也就是说,如果你真的想在脚下拍摄自己,你可以。

That said, if you really want to shoot your self in the foot you can.

您可以使用这样的分配器钩子修改 DEBUG运行时更改 默认填充这将只适用于HEAP分配的对象!

You can change the default fill for the windows DEBUG runtime by using an allocator hook like this. This will only work on HEAP allocated object!

int main(int argc,char** arv)
{
  // Call first to register hook
  _CrtSetAllocHook(&zero_fill);
  // Do other stuff
  malloc(100);
}


int zero_fill(int nAllocType,
              void* pvData,
              size_t nSize,
              int nBlockUse,
              long lRequest,
              const unsigned char *szFileName,
              int nLine )
{
  /// Very Importaint !!
  /// infinite recursion if this is removed !!
  /// _CRT_BLOCK must not do any thing but return TRUE
  /// even calling printf in the _CRT_BLOCK will cause
  /// infinite recursion
  if ( nBlockUse == _CRT_BLOCK )
    return( TRUE );
  switch(nAllocType)
  {
  case _HOOK_ALLOC:
  case _HOOK_REALLOC:
    // zero initialize the allocated space.
    memset(pvData,0,nSize);
    break;
  case _HOOK_FREE:
    break;
  }
  return TRUE;
}

这篇关于VC ++中未初始化的内存块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 08:52