我想知道为什么在运行以下代码时,t
的值在调用get
之后与以前相同。
我有一种感觉,问题是c = tmp
第11行的重新分配——但希望有人能给我指明正确的方向?
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
BOOL get(COMPUTER_NAME_FORMAT f, WCHAR* c) {
DWORD s = 0;
WCHAR* tmp = NULL;
GetComputerNameExW(f, tmp, &s);
tmp = (WCHAR*)realloc(tmp, sizeof(WCHAR) * s);
GetComputerNameExW(f, tmp, &s);
c = tmp;
return TRUE;
}
void _tmain(int argc, _TCHAR* argv[])
{
WCHAR* t = TEXT("thisisatest");
BOOL res = get(ComputerNameDnsHostname, t);
printf("%Lsn", t);
}
为了简洁起见,上面的代码去掉了错误处理代码。此外,我怀疑对GetComputerNameExW((的两次调用之间存在竞争条件。
您只需在get(COMPUTER_NAME_FORMAT f, WCHAR* c)
函数中修改main的t
指针的参数副本。
该效果不会在get
之外传播。您将tmp的值分配给一个临时指针,该指针在get
返回后丢失。
将c
作为WCHAR** c
在get
中传递,如下所示:
BOOL get(COMPUTER_NAME_FORMAT f, WCHAR** c){
//stuff
tmp = (WCHAR*)realloc(tmp, sizeof(WCHAR) * s);
*c=tmp;
//other stuff
}