1

I am following Microsoft's guidelines on how to work around this warning but it doesn't seem to work.

I add all the checks but, when I copy the 'expanded' pointer tmp to ptr and try to use it, I get another warning:

Warning C6200 Index '1' is out of valid index range '0' to '0' for non-stack buffer 'ptr'

void main(void)
{
    int* ptr, * tmp;//I start with two pointers
    ptr = (int*)malloc(1 * sizeof(int));
    ptr[0] = 10;
    if (ptr != NULL)//make sure ptr is not null.
    {
        tmp = (int*)realloc(ptr, 5 * sizeof(int));//expand tmp up to 5
        if (tmp != NULL)//make sure it went well.
        {
            ptr = tmp;
            ptr[1] = 20;
/*
Warning C6200   Index '1' is out of valid index range '0' to '0' for non-stack buffer 'ptr'.    
 */
        }
    }
 }
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
Andrés Sanchez
  • 99
  • 1
  • 10

1 Answers1

3

The C6011 warning is valid and can be addressed by moving the ptr[0] = 10; line to after you have checked that the initial ptr value returned by malloc is not NULL.

However, the C6200 warning is just plain wrong, as discussed, for example, in this blog.

There are a couple of 'tricks' you can use to silence this spurious warning, as shown in the code below:

#include <stdlib.h>

int main(void)
{
    int *ptr, *tmp;//I start with two pointers
    ptr = malloc(1 * sizeof(int));
//  ptr[0] = 10; // Move this to AFTER non-NULL check to avoid C6011...
    if (ptr != NULL)//make sure ptr is not null.
    {
        ptr[0] = 10; // ... moved to here!
        tmp = realloc(ptr, 5 * sizeof(int));//expand tmp up to 5
        if (tmp != NULL)//make sure it went well.
        {
            ptr = tmp;
        //  ptr[1] = 20;
            tmp[1] = 20; // This 'trivial' change silences the C6200
        //  (ptr = tmp)[1] = 20; // ... or you can use this in place of the above two lines!
        }
    }
    free(ptr);
    return 0;
}

Alternatively, you can add a #pragma warning(suppress:6200) line immediately before the ptr[1] = 20; – this will disable that warning 'temporarily' and only for the next line, as described here:

suppress    Pushes the current state of the pragma on the stack, disables the specified warning for the next line, and then pops the warning stack so that the pragma state is reset.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83