0

How can i solve the C6386 warning that occurs at the line inside for loop?

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."

Function can be found below:

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;
    }
}
  • 1
    Are you sure the error refers to this exact code? I don't see any problem with it. One note though, better not name variables the same as function. – Eugene Sh. Apr 30 '21 at 16:17

1 Answers1

3

Found the reason why this warning occurs from here.

For this particular example, since 'size + 1' never becomes 0, this warning can be ignored. And if i check that 'size + 1' is greater than 0 before calling malloc the warning goes away.