Visual Studio 2019 started showing Code Analysis warnings as in-editor green squiggles by default. These may be extremely useful for students learning C programming, because they catch classical mistakes, such as off by one array accesses.
Unfortunately false positives may completely ruin the learning experience and I fear that I will have to ask the students to disable the feature in order to avoid having them worry on non existing problems.
This short snippet doesn't cause any warning:
#include <stdlib.h>
int main(void)
{
size_t n = 6;
int *v = malloc(n * sizeof(int));
if (v == NULL) {
return 1;
}
for (size_t i = 0; i < n; ++i) {
v[i] = i;
}
free(v);
return 0;
}
Unfortunately, if you move the allocation in a function, like this:
#include <stdlib.h>
int *test(size_t n)
{
int *v = malloc(n * sizeof(int));
if (v == NULL) {
return NULL;
}
for (size_t i = 0; i < n; ++i) {
v[i] = i;
}
return v;
}
int main(void)
{
size_t n = 6;
int *v = test(n);
free(v);
return 0;
}
you get a warning C6386: Buffer overrun while writing to 'v': the writable size is 'n*sizeof(int)' bytes, but '8' bytes might be written.
Even reading on Stack Overflow, I don't get where the '8'
comes from, but, more importantly, why it fails to recognize that i
will never be out of range.
So the question is: is there a way to write this type of code in a way that will not generate the warning?
I know that I can go to Tools > Options > Text Editor > C/C++ > Experimental > Code Analysis
and set Disable Code Analysis Squiggles
to True
, or use a #pragma warning(disable:6386)
, but I'd rather avoid it, and certainly avoid suggesting my students the latter.