code_junkie

Uninitialized memory blocks in VC++

Nov 10th, 2011
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. // Call first to register hook
  2. _CrtSetAllocHook(&zero_fill);
  3.  
  4.  
  5.  
  6. int zero_fill(int nAllocType,
  7. void* pvData,
  8. size_t nSize,
  9. int nBlockUse,
  10. long lRequest,
  11. const unsigned char *szFileName,
  12. int nLine )
  13. /// Very Importaint !!
  14. /// infinite recursion if this is removed !!
  15. /// _CRT_BLOCK must not do any thing but return TRUE
  16. /// even calling printf in the _CRT_BLOCK will cause
  17. /// infinite recursion
  18. if ( nBlockUse == _CRT_BLOCK )
  19. return( TRUE );
  20. switch(nAllocType)
  21. {
  22. case _HOOK_ALLOC:
  23. case _HOOK_REALLOC:
  24. // zero initialize the allocated space.
  25. memset(pvData,0,nSize);
  26. break;
  27. case _HOOK_FREE:
  28. break;
  29. }
  30. return TRUE;
  31.  
  32. char * p = new char[16]; // 16 bytes of random trash
  33. strcpy(p, "StackOverflow"); // 13 characters, a '' terminator, and two bytes of trash
  34. delete [] p; // return 16 bytes to the heap, but nothing else changes;
  35.  
  36. if (p != NULL) // Why would p be NULL? It was never set to NULL
  37. ASSERT(p[0] == 'S'); // In debug, this will crash, because p = 0xfeeefeee and
  38. // dereferencing it will cause an error.
  39. // Release mode may or may or may not work, depending on
  40. // other memory operations
  41.  
  42. int *ptr=0;
  43.  
  44. #define SafeDelete(mem) { delete mem; mem = NULL; }
  45. #define SafeDeleteArray(mem) { delete [] mem; mem = NULL; }
Add Comment
Please, Sign In to add comment