抱歉,如果这是重复的帖子。 我目前遇到的一个问题是,我在这段代码上收到一条警告,提示“写入‘titleTextPointer’时缓冲区溢出”,但我相当确定不会有缓冲区溢出(这是假设所有标题以 ' ' 结尾)
const char* title = "test";
int titleLen = 0;
while(title[titleLen] != '\0'){
titleLen++;
}
WCHAR* titleTextPointer = (WCHAR*)malloc(sizeof(WCHAR) * (titleLen + 1)); //creates a new wide char list(WCHAR array) +1 for a terminating character(\0)
if (titleTextPointer == NULL) { printf("error occured while locating space\n"); return 1; }
for (int i = 0; i < titleLen; i++) {//iterats through lists and transfers memory
titleTextPointer[i] = title[i]; //actual transfer (char is 1byte, wide char is 2 bytes)
}
titleTextPointer[titleLen] = '\0'; //adds the last terminating value to properly use the widechar in function
我尝试分配更多空间(+2),但警告仍然弹出。
您发布的代码没有表现出任何缓冲区溢出,因此我认为您的 IDE 出现了幻觉。这是您应该发布的示例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <wchar.h>
int main(void) {
const char *title = "test";
size_t titleLen = strlen(title);
wchar_t *titleTextPointer = malloc(sizeof *titleTextPointer * (titleLen + 1));
if (!titleTextPointer) {
printf("error occured while locating space\n");
return 1;
}
for (int i = 0; i <= titleLen; i++)
titleTextPointer[i] = title[i];
}