如果这是一个重复的帖子,很抱歉. 我目前遇到了一个问题,我收到关于这段代码的警告,显示为C6386: Buffer overrun while writing to 'titleTextPointer',但我相当确定运行时不会有缓冲区(假设所有标题都以'\0'结尾):

    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++) { //iterates 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

code with error attached

我已try 分配更多空间(+2),但仍弹出警告.

推荐答案

您发布的代码没有显示任何缓冲区溢出,因此我认为您的IDE出现了幻觉.我不知道什么是WCHAR,在我的系统中,wchar_t是4字节.请注意@Ikegami的观点,直接赋值可能不是从char *wchat_t *的正确映射.下面是一个最小的(不可重现的)示例:

#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 occurred while locating space\n");
        return 1;
    }
    for (size_t i = 0; i <= titleLen; i++)
        titleTextPointer[i] = (unsigned char) title[i];
    free(titleTextPointer);
}

C++相关问答推荐

有什么方法可以检测SunOS上的SparcWorks吗?

在C中使用JMP_buf数组进行线程化(在xv6中测试)

__VA_OPT__(,)是否可以检测后面没有任何内容的尾随逗号?

正在try 将文件/文件夹名从目录 struct 存储到链接列表

为什么GCC在每次循环迭代时都会生成一个数组的mov&S使用[]访问数组?(-03,x86)

如何将字符串传递给函数并返回在C中更改的相同字符串?

正确的TCP/IP数据包 struct

C++中矢量类型定义和数据保护的高效解决方案

在CLANG中调试预处理器宏

Flose()在Docker容器中抛出段错误

Vcpkg的配置文件

CGO:如何防止在使用CGO在包中包含C头文件时出现多个定义...&q;错误?

S的这种管道实施有什么问题吗?

将返回的char*设置为S在函数中定义的字符串文字可能会产生什么问题?

强制转换变量以在 struct 中蚕食

为什么这个代码的最后一次迭代不能正常工作?

我的代码可以与一个编译器一起使用,但不能与其他编译器一起使用

函数指针作为函数参数 - 应该使用 const 吗?

clion.我无法理解 Clion 中发生的 scanf 错误

与 C 相比,C++ 中无副作用的无限循环的好处是 UB?