views:

214

answers:

2

I've got a function that takes a pointer to a buffer, and the size of that buffer (via a pointer). If the buffer's not big enough, it returns an error value and sets the required length in the out-param:

// FillBuffer is defined in another compilation unit (OBJ file).
// Whole program optimization is off.
int FillBuffer(__int_bcount_opt(*pcb) char *buffer, size_t *pcb);

I call it like this:

size_t cb = 12;
char *p = (char *)malloc(cb);
if (!p)
    return ENOMEM;

int result;
for (;;)
{
    result = FillBuffer(p, &cb);
    if (result == ENOBUFS)
    {
        char *q = (char *)realloc(p, cb);
        if (!q)
        {
            free(p);
            return ENOMEM;
        }

        p = q;
    }
    else
        break;
}

Visual C++ 2010 (with code analysis cranked to the max) complains with 'warning C6001: Using uninitialized memory 'p': Lines: ...'. It reports line numbers covering pretty much the entire function.

Visual C++ 2008 doesn't. As far as I can tell, this code's OK. What am I missing? Or what is VC2010 missing?

A: 

You did not check if the first malloc() is ok. This leads to the warning.

alemjerus
malloc will alwavs return something so p will always get a value. I don't think this is the issue
Arve
FillBuffer accepts NULL, and puts the appropriate required size in the out-param.
Roger Lipscombe
+3  A: 

This has to be a bug in VS.2010. Wrapping malloc removes the warning:

char * mymalloc(int i)
{
return (char *) malloc(i);
}

...

void *r = mymalloc(cb);

char *p;

p = (char *) malloc(cb)

Makes the warning go away

Arve
Hmmm. I tried that. It didn't make it go away. Most odd.
Roger Lipscombe
You are right. My mistake, it needs to be char *p = NULL to make the warnings go away. (Should probably down vote myself). (I think I did a rebuild and not an analyse by mistake)
Arve
Thanks for the confirmation. I've raised a bug on Connect.
Roger Lipscombe
If you are not happy with your own answer you can edit or remove it and make it easier for later visitors (make sure they understand the answer is not such even if they don't go into comments)
David Rodríguez - dribeas