_CrtIsValidHeapPointer_CrtIsValidHeapPointer
Проверяет, находится ли заданный указатель в куче, выделенной определенной библиотекой среды выполнения C, но не обязательно библиотекой CRT вызывающей функции.Verifies that a specified pointer is in a heap allocated by some C run-time library, but not necessarily by the caller's CRT library. В версиях CRT, выпущенных до выхода Visual Studio 2010, эта функция проверяла, находится ли заданный указатель в локальной куче (только отладочная версия).In versions of the CRT before Visual Studio 2010, this verifies that the specified pointer is in the local heap (debug version only).
СинтаксисSyntax
int _CrtIsValidHeapPointer(
const void *userData
);
ПараметрыParameters
userDatauserData
Указатель на начало выделенного блока памяти.Pointer to the beginning of an allocated memory block.
Возвращаемое значениеReturn Value
_CrtIsValidHeapPointer возвращает значение true, если указанный указатель находится в куче, совместно используемой всеми экземплярами библиотеки CRT._CrtIsValidHeapPointer returns TRUE if the specified pointer is in the heap shared by all CRT library instances. В версиях CRT, выпущенных до выхода Visual Studio 2010, эта функция возвращала значение TRUE, если указатель находился в локальной куче.In versions of the CRT before Visual Studio 2010, this returns TRUE if the specified pointer is in the local heap. В противном случае функция возвращает значение FALSE.Otherwise, the function returns FALSE.
КомментарииRemarks
Использовать эту функцию не рекомендуется.We do not recommend that you use this function. Начиная с библиотеки CRT в Visual Studio 2010, все библиотеки CRT используют одну и ту же кучу операционной системы — кучу процесса.Starting with the Visual Studio 2010 CRT library, all CRT libraries share one OS heap, the process heap. Функция _CrtIsValidHeapPointer сообщает, выделен ли указатель в куче CRT, но не в том, что она была выделена библиотекой CRT вызывающей стороны.The _CrtIsValidHeapPointer function reports whether the pointer was allocated in a CRT heap, but not that it was allocated by the caller's CRT library. Возьмем для примера блок, выделенный с помощью библиотеки CRT в составе Visual Studio 2010.For example, consider a block allocated by using the Visual Studio 2010 version of the CRT library. Если функция _CrtIsValidHeapPointer , экспортируемая с помощью версии библиотеки CRT для Visual Studio 2012, проверяет указатель, возвращается значение true.If the _CrtIsValidHeapPointer function exported by the Visual Studio 2012 version of the CRT library tests the pointer, it returns TRUE. Необходимости в такой проверке больше нет.This is no longer a useful test. В версиях библиотеки CRT до Visual Studio 2010 эта функция используется для проверки наличия того или иного адреса памяти в локальной куче.In versions of the CRT library before Visual Studio 2010, the function is used to ensure that a specific memory address is within the local heap. Локальная куча обращается к куче, созданной и управляемой определенным экземпляром библиотеки среды выполнения C.The local heap refers to the heap created and managed by a particular instance of the C run-time library. Если библиотека динамической компоновки (DLL) содержит статическую ссылку на библиотеку среды выполнения, она имеет свой собственный экземпляр кучи среды выполнения, а значит и собственную кучу, не зависящую от локальной кучи приложения.If a dynamic-link library (DLL) contains a static link to the run-time library, it has its own instance of the run-time heap, and therefore its own heap, independent of the application's local heap. Если _DEBUG не определено, вызовы _CrtIsValidHeapPointer удаляются во время предварительной обработки.When _DEBUG is not defined, calls to _CrtIsValidHeapPointer are removed during preprocessing.
Так как эта функция возвращает значение TRUE или FALSE, ее можно передать в один из макросов _ASSERT для создания простого механизма обработки ошибок отладки.Because this function returns TRUE or FALSE, it can be passed to one of the _ASSERT macros to create a simple debugging error handling mechanism. Приведенный ниже пример вызывает сбой утверждения, если указанный адрес находится не в локальной куче.The following example causes an assertion failure if the specified address is not located within the local heap:
_ASSERTE( _CrtIsValidHeapPointer( userData ) );
Дополнительные сведения о том, как _CrtIsValidHeapPointer можно использовать с другими функциями и макросами отладки, см. в разделе macros for Reporting.For more information about how _CrtIsValidHeapPointer can be used with other debug functions and macros, see Macros for Reporting. Сведения о выделении, инициализации и управлении блоками памяти в отладочной версии базовой кучи, см. в статье CRT Debug Heap Details.For information about how memory blocks are allocated, initialized, and managed in the debug version of the base heap, see CRT Debug Heap Details.
ТребованияRequirements
ПодпрограммаRoutine | Обязательный заголовокRequired header |
---|---|
_CrtIsValidHeapPointer_CrtIsValidHeapPointer | <crtdbg.h> |
Дополнительные сведения о совместимости см. в разделе Compatibility.For more compatibility information, see Compatibility.
БиблиотекиLibraries
Только отладочные версии библиотек времени выполнения языка C.Debug versions of C run-time libraries only.
ПримерExample
В приведенном ниже примере показано, как проверить допустимость памяти, если используется библиотека среды выполнения C до Visual Studio 2010.The following example demonstrates how to test whether memory is valid when it is used with C run-time libraries before Visual Studio 2010. Пример приведен для пользователей предыдущих версий библиотеки кодов CRT.This example is provided for users of legacy CRT library code.
// crt_isvalid.c
// This program allocates a block of memory using _malloc_dbg
// and then tests the validity of this memory by calling
// _CrtIsMemoryBlock,_CrtIsValidPointer, and _CrtIsValidHeapPointer.
#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <crtdbg.h>
#define TRUE 1
#define FALSE 0
int main( void )
{
char *my_pointer;
// Call _malloc_dbg to include the filename and line number
// of our allocation request in the header information
my_pointer = (char *)_malloc_dbg( sizeof(char) * 10,
_NORMAL_BLOCK, __FILE__, __LINE__ );
// Ensure that the memory got allocated correctly
_CrtIsMemoryBlock((const void *)my_pointer, sizeof(char) * 10,
NULL, NULL, NULL );
// Test for read/write accessibility
if (_CrtIsValidPointer((const void *)my_pointer,
sizeof(char) * 10, TRUE))
printf("my_pointer has read and write accessibility.\n");
else
printf("my_pointer only has read access.\n");
// Make sure my_pointer is within the local heap
if (_CrtIsValidHeapPointer((const void *)my_pointer))
printf("my_pointer is within the local heap.\n");
else
printf("my_pointer is not located within the local"
" heap.\n");
free(my_pointer);
}
my_pointer has read and write accessibility.
my_pointer is within the local heap.