简体   繁体   English

我该如何解决这个警告 C6386

[英]How can i solve this warning C6386

How can i solve the C6386 warning that occurs at the line inside for loop?如何解决在 for 循环内的行中出现的 C6386 警告?

reverseString[i] = str[size - i - 1]; Warning occurs on this line.此行出现警告。

The exact error is: "C6386: Buffer overrun while writing to 'reverseString': the writable size is '((size+1))*sizeof(char)' bytes, but '2' bytes might be written."确切的错误是:“C6386:写入‘reverseString’时缓冲区溢出:可写大小为‘((size+1))*sizeof(char)’字节,但可能写入‘2’字节。”

Function can be found below: Function 可以在下面找到:

char* reverseString(char* str) {
    if (str == NULL) {
        printf("input error\n");
        return NULL;
    }

    int size = strlen(str);
    char* reverseString = malloc((size + 1) * sizeof(char));
    if (reverseString != NULL) {
        for (int i = 0; i < size; i++) {
            reverseString[i] = str[size - i - 1];
        }
        reverseString[size] = '\0';
        
        return reverseString;
    }
    else {
        printf("error while allocating memory\n");
        return NULL;
    }
}

Found the reason why this warning occurs from here .这里找到发生此警告的原因。

For this particular example, since 'size + 1' never becomes 0, this warning can be ignored.对于这个特定的例子,因为 'size + 1' 永远不会变成 0,所以可以忽略这个警告。 And if i check that 'size + 1' is greater than 0 before calling malloc the warning goes away.如果我在调用 malloc 之前检查“size + 1”是否大于 0,警告就会消失。

According to here I think the warning you get belongs to the line根据这里,我认为您收到的警告属于该行

reverseString[size] = '\0';

not the line you mentioned.不是你提到的那条线。 In the mentioned link it requires you to set reverseString[size-1] = '\0';在提到的链接中,它要求您设置reverseString[size-1] = '\0'; . .

Please try it.请尝试一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM