Reputation: 31
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;
}
}
Upvotes: 0
Views: 1314
Reputation: 31
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.
Upvotes: 3