我的WCHAR*变量在我的C项目中打印unicode字符



我为我的C项目做了一个小的链接地图。我用这张地图来存放我的支票,我把当前文件路径放到映射中。如果再次请求相同的文件路径,则必须从缓存映射中获取值。

struct StrBoolNode {
const WCHAR* key;
BOOL* value;
struct StrBoolNode* next;
};
struct StrBoolTable {
struct StrBoolNode* first;
};
BOOL* strBoolTable_get(struct StrBoolTable* table, const WCHAR* key) {
wprintf(L"TEST strBoolTable_get %s n", key);
struct StrBoolNode* node = table->first;
while (node != NULL) {
wprintf(L"strBoolTable_get WHILE %s n", node->key);  <<< prints here broken
if (wcscmp(key, node->key) == 0) return node->value;
node = node->next;
}
return NULL;
}
void strBoolTable_push(struct StrBoolTable* table, const WCHAR* key, BOOL value) {
wprintf(L"TEST strBoolTable_push 1 %s n", key); <<< prints here normal
struct StrBoolNode* tmp = (StrBoolNode*)malloc(sizeof(struct StrBoolNode));
tmp->key = cloneKey;
tmp->value = (BOOL*)malloc(sizeof(BOOL));
*(tmp->value) = value;
tmp->next = NULL;

wprintf(L"TEST strBoolTable_push 2 %s n", tmp->key);  <<< prints here normal
if (table->first == NULL) {
table->first = tmp;
wprintf(L"TEST strBoolTable_push 3 %s n", table->first->key);  <<< prints here normal
return;
}
struct StrBoolNode* node = table->first;
while (node->next != NULL) {
node = node->next;
}
node->next = tmp;
wprintf(L"TEST strBoolTable_push 4 %s n", node->next->key);  <<< prints here normal
}
struct StrBoolTable cacheMap = { NULL };
WCHAR szFileName[MAX_PATH];
HMODULE hModule = NULL;
GetModuleHandleEx(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
(LPCTSTR)retAddr,
&hModule);
GetModuleFileNameW(hModule, szFileName, 2048);

BOOL* cacheVal = strBoolTable_get(&cacheMap, szFileName);
if (cacheVal != NULL) return *cacheVal;

wprintf(L"Check => %s n", szFileName);   <<<< szFileName prints normal

strBoolTable_push(&cacheMap, szFileName, TRUE);
return TRUE;

当将object压入到这个映射中时没有问题,但是当我迭代并打印object中的键时,它返回unicode字符。像这样"Ï,♥"。为什么我的对象的键稍后更改为此?

我在打印错误的地方标记了<<<在代码中>

我在strBoolTable_push中看到的cloneKey是什么?它在任何地方都有声明。代码是如何编译的?

我的灵媒提示你正在推送一个局部数组变量:

WCHAR szFileName[MAX_PATH];

放到你的集合中。但是一旦声明szFileName的函数返回,所有的赌注都取消了(未定义的行为)。内存空间很容易被函数返回后发生的任何事情回收和覆盖。当这种情况发生时,您的key在链表中被损坏。

确保在将字符串key持久化到集合之前复制了它:

void strBoolTable_push(struct StrBoolTable* table, const WCHAR* key, BOOL value) {

wprintf(L"TEST strBoolTable_push 1 %s n", key); <<< prints here normal
struct StrBoolNode* tmp = (StrBoolNode*)malloc(sizeof(struct StrBoolNode));
// wcsdup is equivalent to saying: tmp->key = malloc((wcslen(key)+1)*sizeof(WCHAR))); wcscpy(tmp->key, key);
tmp->key = _wcsdup(key); 

同样,当您从列表中取出一个节点时,请确保将每个节点的keyvalue成员都free

最新更新