1、释放问题
关于这个函数,wdk文档中有下面这段话
The Buffer member of DestinationString is initialized to point to SourceString. The length and maximum length for DestinationString are initialized to the length of SourceString. If SourceString is NULL, the length is zero.
如果不注意,释放的时候可能会造成蓝屏。
例如:
UNICODE_STRING ustrName;
ustrName.Buffer=ExAllocatePool(PagedPool,128);
RtlInitUnicodeString(&ustrName,L"zhangsan");
这时候如果调用ExFreePool(ustrName.Buffer)就会触发蓝屏,因为ustrName.Buffer已经指向常量区
上面的初始化过程等同于下面的语句:
ustrName=RTL_CONSTANT_STRING(L"zhangsan");
在ntdef.h头文件中可以看到RTL_CONSTANT_STRING定义如下:
#define RTL_CONSTANT_STRING(s) \
{ \
sizeof( s ) - sizeof( (s)[0] ), \
sizeof( s ) / sizeof(_RTL_CONSTANT_STRING_type_check(s)), \
_RTL_CONSTANT_STRING_remove_const_macro(s) \
}
2、初始化问题
WCHAR wcPath[MAX_PATH]={0};
UNICODE_STRING ustrName;
RtlInitUnicodeString(&ustrName,wcPath);
ustrName.MaximumLength=sizeof(WCHAR)*MAX_PATH;
如果没有加上最后一行,ustrName.MaximumLength=2
后面如果继续使用RtlCopyUnicodeString等函数很可能会失败,只能复制第一个字符。
上面这个初始化过程可以使用RtlInitEmptyUnicodeString 这个函数,
RtlInitEmptyUnicodeString(&ustrName, wcPath, sizeof(wcPath));
本文探讨了RtlInitUnicodeString函数在使用过程中可能出现的问题,包括释放问题和初始化问题。当SourceString为NULL时,直接释放Buffer会导致蓝屏。另外,未正确设置MaximumLength可能导致后续操作失败。解决方案包括理解Buffer指向常量区的特性以及使用RtlInitEmptyUnicodeString进行安全初始化。
596

被折叠的 条评论
为什么被折叠?



