If this code triggers a warning

I came across a code similar to the one below, which is legal, although not very smart. Two stack variables in the same function in an area simultaneously with the same name are legal, but can cause problems. (Read: I just wasted half an hour debugging this). At level 4 on VS2010 (highest level), I would hope that this would catch it. Am I missing something, or is it time to hit the whole code base with lint at a time? Can a static analysis tool like lint even catch the names of such conflicts?

char *x = strchr(Buffer,' '); if (x) { *x = 0; x++; char *x = strchr(x,' ') if (x) *x = 0; } 
+4
source share
2 answers

PC-Lint will detect this. The following code:

 main (int argc, char *argv []) { char *x = 0; if (x) { char *x = 0; } } 

It gives a warning:

 main.cpp 6 Warning 578: Declaration of symbol 'x' hides symbol 'x' (line 3) 
+2
source

Edit: I did not notice this when I wrote the original answer (see below). The code you posted is illegal and causes undefined behavior. The offensive line is:

 char *x = strchr(x,' '); 

Here, x in the strchr call strchr not refer to x defined in the application area, but to x defined earlier on the same line. Therefore, this line is read from an uninitialized variable, which leads to undefined behavior. From the C ++ standard

ยง3.3.2 / 1 [basic.scope.pdecl]
The declaration point for the name immediately after its full declaration (section 8) and before its initializer (if any), except as noted below. [Example:

  int x = 12; { int x = x; } 

Here the second x is initialized with its own (undefined) value. -end example]

GCC complains if the corresponding line in the example below is changed to

 int x = 21 + x; // generates "warning: x is used uninitialized in this function" 

And duplicating your strchr example on VS2012 generates this warning (in /W1 and above):

 warning C4700: uninitialized local variable 'x' used 

The original answer follows (not entirely accurate):

There is nothing illegal in the code. You have entered a new scope by adding curly braces, and you are allowed to define variables in the new scope, even if these variable names were previously defined in the application scope.

All references to the variable after the new definition will refer to the local variable instead of the one located in the enclosing area, until the local variable expires. The following code does not generate any warnings about GCC even when compiling with -pedantic -Wall -Wextra

 #include <iostream> int main() { int x = 42; { std::cout << x << '\n'; int x = 21; std::cout << x << '\n'; } std::cout << x << '\n'; } 

Output:

 42 21 42 

I do not know if this tool or the static analysis tool will understand. This is legal but not recommended.

+2
source

Source: https://habr.com/ru/post/1481237/


All Articles