Search code examples
c++cinitializationcompiler-warnings

C6001 on using the address of uninitialized value. Why?


This here is my C++ code:

void somefn(char* string){
    char *current, *next;
    current = strtok_s(string, "a", &next);  // next is unitialized -> C6001 in VS 2020
}

int main(){
    char buf[] = "foobar";
    return 0;
}

which is deemed warning-worthy by a certain compiler with certain flags (should not matter, I believe).

The only questions are:

  1. Does this lead to an undefined behavior? I currently believe that an address of an uninitialized variable is a compile-time constant.
  2. Can this be for any reason considered bad practice? Why?

EDIT: Promised screenshot Code screenshot


Solution

  • The reference documentation for strtok_s shows that the above code is perfectly valid assuming that string is not a NULL pointer. Whether "an address of an uninitialized variable is a compile-time constant" is completely irrelevant and doesn't have anything to do with the diagnostic. The compiler thinks you are using uninitialized memory.

    However the 4th parameter to strtok_s, as per documentation, needs to have the pointed-to pointer initialized (by an earlier call to strtok_s) only if the first parameter is NULL.

    The compiler is being rather picky, it seems. It looks like the compiler cannot prove to itself that string will never be NULL here, so it's complaining about this.

    But, if you never call strtok_s here with a NULL pointer here then there's nothing wrong with this.