﻿# Let's check Scilab

What powerful tools do you know for complex mathematical computations? One example is the open\-source project Scilab\. We analyzed its source code to see what errors we could uncover\. In this article, we'll show how static analysis can help detect them\.

![1429_Scilab/image1.png](https://import.viva64.com/docx/blog/1429_Scilab/image1.png)

## What's our topic today?

[Scilab](https://www.scilab.org/) is an open\-source, cross\-platform project designed for scientific and engineering computing\. It's widely used in manufacturing, automotive engineering, medicine, and other fields for solving complex mathematical problems\. The project's wide range of uses requires the highest standards for the quality and reliability of its code\.

We used [PVS\-Studio](https://pvs-studio.com/en/) static analyzer to check the Scilab source code\. In this article, we highlighted the most interesting errors we found\. Our goal is to show developers how static analysis can help make the projects even better\.

<details>
   <summary>A few words about PVS\\\-Studio</summary>

PVS\-Studio is a static analyzer that has been helping developers detect errors in C, C\+\+, C\#, Java, Go, JavaScript, and TypeScript code for over 18 years\. We also provide excellent [technical support](https://pvs-studio.com/en/blog/posts/1359/)\.


</details>
Static analysis is a step in the development process that complements other quality assurance methods, such as testing and code reviews\. It helps developers detect bugs and potential vulnerabilities early in the development process\. This enables teams to devote more time to implementing new features and less time to fixing code issues\.

This article doesn't cover all the issues we detected\. Instead, we've chosen the examples we found most intriguing\. [Try PVS\-Studio for free](https://pvs-studio.com/en/pvs-studio/try-free/) to view the full report or check your own project\.

**Note\.** We checked the project at the time of the [`30a3695a`](https://gitlab.com/scilab/scilab/-/commit/30a3695a9aecd6abfde2a5aa27f4cd98f5ee41d5) commit using [PVS\-Studio 8\.00](https://pvs-studio.com/en/blog/posts/1406/)\.

## Errors

### Handling pointers

**Snippet 1**

The PVS\-Studio warning: [V611](https://pvs-studio.com/en/docs/warnings/v611/) \[CWE\-762, CERT\-MEM51\-CPP, SEC\-MEMORY\] The memory was allocated using the 'operator new' but was released using the 'operator delete\[\]'\. The 'delete ptr;' statement should be used instead\. fromws\_c\.cpp 335

```cpp
SCICOS_BLOCKS_IMPEXP void fromws_c(scicos_block* block, int flag)
{
  // ....
  fromwork_struct** work = (fromwork_struct**) block->work;
  fromwork_struct* ptr = nullptr;
  // ....
  *work = new fromwork_struct(); // <=
  ptr = *work;                   // <=
  // ....
  
  if (ptr_T[j] > ptr_T[j + 1])
  {
      Coserror(_("The time vector should be an increasing vector.\n"));
      *work = nullptr;
      delete[] ptr->workt;
      FREE(ptr->work);
      delete[] ptr;           // <=
      return;
  }
  // ....
}
```

The issue is clear: the developers used an incorrect deallocation method\. Memory for the element that `ptr` points to is allocated using `new` and deallocated using `delete[]`\. What potential issues could arise from this?

According to the [C\+\+ standard](https://eel.is/c++draft/expr.delete#2), if we allocate memory for a single object but free it using `delete[]`, the program's behavior is undefined\. In reality, `delete[]` expects metadata before the memory block that stores the number of elements allocated by `new T[N]`\. If the metadata isn't there, the operator may read garbage\. As a result, it may call the wrong number of destructors or attempt to free an incorrect address\.

If you still believe that undefined behavior is just a myth, [this article](https://pvs-studio.com/en/blog/posts/cpp/1024/) might change your mind\.

To fix the code, we need to remove `[]` when clearing the `ptr` pointer:

```cpp
delete ptr;
```

**Snippet 2**

The PVS\-Studio warning: [V595](https://pvs-studio.com/en/docs/warnings/v595/) \[CWE\-476, CERT\-EXP12\-C, SEC\-NULL\] The 'values' pointer was utilized before it was verified against nullptr\. Check lines: 465, 466\. sundials\_hashmap\.c 465

```cpp
SUNErrCode SUNHashMap_Values
  (SUNHashMap map, void*** values, int64_t value_size)
{
  int count = 0;

  if (!map) { return SUN_ERR_ARG_CORRUPT; }

  *values = (void**)malloc(SUNHashMap_Capacity(map) * value_size);
  if (!values) { return SUN_ERR_MALLOC_FAIL; }
  // ....
}
```

Manual memory management can lead to various errors\. Here, the `values` pointer is passed as a function parameter\. We dereference it and check for `NULL` on the next line\. If the pointer is `null`, dereferencing it will result in undefined behavior; so, the check below is meaningless\. In reality, the compiler can simply remove the entire `if (!values)` block\. It sees that the pointer is already in use, so it assumes it's valid and that the check is redundant\.

The developers might have wanted to check the result of the `malloc` function, which returns `NULL` if memory allocation fails\. However, the typo triggers the wrong check, and dereferencing happens further down in the code:

```cpp
for (int64_t i = 0; i < SUNHashMap_Capacity(map); i++)
{
  SUNHashMapKeyValue kvp = 
    *SUNStlVector_SUNHashMapKeyValue_At(map->buckets, i);
  if (kvp) { (*values)[count++] = kvp->value; }  // <=
}
```

The PVS\-Studio warning: [V522](https://pvs-studio.com/en/docs/warnings/v522/) \[CWE\-690, CERT\-MEM52\-CPP, SEC\-NULL\] There might be dereferencing of a potential null pointer '\* values'\. Check lines: 472, 465\. sundials\_hashmap\.c 472

To fix the code, we'll add a check for the `values` pointer and verify that memory is allocated at `*values`:

```cpp
if (!map || !values) { return SUN_ERR_ARG_CORRUPT; }

*values = (void**)malloc(SUNHashMap_Capacity(map) * value_size);
if (!*values) { return SUN_ERR_MALLOC_FAIL; }
```

**Snippet 3**

The PVS\-Studio warning: [V558](https://pvs-studio.com/en/docs/warnings/v558/) \[CWE\-562, CERT\-DCL30\-C, SEC\-MEMORY\] Function returns the reference to temporary local object: tmp\. [matrixiterator\.hxx 527](https://gitlab.com/scilab/scilab/-/blob/30a3695a9aecd6abfde2a5aa27f4cd98f5ee41d5/scilab/modules/ast/includes/types/matrixiterator.hxx#L527)

```cpp
template<bool AsVector = false> struct Coords : Coords2DIterator
{
  // ....
  Coords& operator++(int)
  {
    Coords tmp(*this);
    ++(*this);
    return tmp;
  }
  // ....
}
```

It looks like the developers copied the prefix increment implementation and used it for the postfix increment by simply adding a dummy parameter of the `int` type\.

That said, the best approach when implementing such operators is to use semantics similar to those of built\-in types\. A postfix increment stores the previous value, produces a side effect, and returns a prvalue with the previous value\. Here, an lvalue reference to the `tmp` local object is returned\. Using it in the caller function results in undefined behavior\.

To avoid this, we need to return the object by value:

```cpp
Coords operator++(int)
{ /* .... */ }
```

The [code below](https://gitlab.com/scilab/scilab/-/blob/30a3695a9aecd6abfde2a5aa27f4cd98f5ee41d5/scilab/modules/ast/includes/types/matrixiterator.hxx#L555-560) contains an explicit specialization of this structure where the operator is implemented correctly\.

**Snippet 4**

The PVS\-Studio warnings:

[V773](https://pvs-studio.com/en/docs/warnings/v773/) \[CWE\-401, CERT\-MEM31\-C, CERT\-MEM51\-CPP, SEC\-LEAKS\] The function was exited without releasing the 'temp\_real' pointer\. A memory leak is possible\. sci\_fft\.cpp 212

[V773](https://pvs-studio.com/en/docs/warnings/v773/) \[CWE\-401, CERT\-MEM31\-C, CERT\-MEM51\-CPP, SEC\-LEAKS\] The function was exited without releasing the 'temp\_imaginary' pointer\. A memory leak is possible\. sci\_fft\.cpp 212

```cpp
#define MALLOC malloc
// ....
int fft_2dim(double *signal_real, double *signal_imaginary, int signal_rows,
  int signal_cols, int inverse, int *buffer_data, int buffer_size)
{
  // ....
  temp_real = (double *)MALLOC(signal_cols * sizeof(double));
  temp_imaginary = (double *)MALLOC(signal_cols * sizeof(double));

  if (temp_real == NULL || temp_imaginary == NULL)
  {
      return 1;
  }
  // ....
}
```

Two memory blocks are allocated, followed by a check whether the operation was successful\. If memory has been allocated for the first buffer but not for the second one, an early exit occurs, and the first buffer remains unallocated\. This is a memory leak\. We can avoid it by releasing both pointers before exiting\.

Here's the fixed code:

```cpp
#define FREE free
// ....
temp_real = (double *)MALLOC(signal_cols * sizeof(double));
temp_imaginary = (double *)MALLOC(signal_cols * sizeof(double));
if (temp_real == NULL || temp_imaginary == NULL)
{
  FREE(temp_real);
  FREE(temp_imaginary);
  return 1;
}
```

### Strange code

**Snippet 5**

The PVS\-Studio warning: [V1061](https://pvs-studio.com/en/docs/warnings/v1061/) \[CERT\-DCL58\-CPP\] Extending the 'std' namespace may result in undefined behavior\. sparseOp\.hxx 39

```cpp
namespace std
{
/* std namespace does not implement complex ordering: 
   we use the lexicographical order   */
typedef double (*cplxFun_t)(std::complex<double> const&);
#ifndef SCI_CPLX_ORDER_SEP21
/* on abs() and arg() according to current practise */
cplxFun_t const mostSignificant (&std::abs);
cplxFun_t const leastSignificant(&std::arg);
#else
/*  on real and imaginary parts as per SEP 21 recommendation.  */
cplxFun_t const mostSignificant (&std::real);
cplxFun_t const leastSignificant(&std::imag);
#endif

template<> struct less<std::complex<double> >
{
  bool operator()(std::complex<double> const& op1,
                  std::complex<double> const& op2) const
  {
    if (mostSignificant(op1) < mostSignificant(op2))
    {
      return true;
    }
    if (mostSignificant(op2) < mostSignificant(op1))
    {
      return false;
    }
    return leastSignificant(op1) < leastSignificant(op2);
  }
};
  // ....
}
```

The standard library doesn't set an order for complex numbers, so the developers came up with their own\. The issue is that the `std` namespace can't be extended\. According to the [standard](https://eel.is/c++draft/namespace.std#1), the program behavior is undefined\. The only [exception](https://eel.is/c++draft/namespace.std#2) to this rule is when a standard library class template is specialized, if the declaration depends on a custom type\. However, `std::complex<double>` isn't one of them\.

How can we fix this? We have two options:

* we can create our own comparator and use it in the appropriate contexts;
* we can create our own wrapper class for `std::complex` and then specialize `std::less` for it\.

![1429_Scilab/image2.png](https://import.viva64.com/docx/blog/1429_Scilab/image2.png)

Another issue worth noting is taking the addresses of standard library functions\. Pay attention to how the `mostSignificant` and `leastSignificant` pointers are initialized in both branches\. Since C\+\+20, the behavior is well\-defined when a program tries to take the address of an [_addressable_](https://timsong-cpp.github.io/cppwp/n4861/namespace.std#def:addressable_function) function\. Otherwise, the behavior is unspecified\. The [std::abs](https://timsong-cpp.github.io/cppwp/n4861/complex.value.ops#itemdecl:3), [std::arg](https://timsong-cpp.github.io/cppwp/n4861/complex.value.ops#itemdecl:4), [std::real](https://timsong-cpp.github.io/cppwp/n4861/complex.value.ops#itemdecl:1), and [std::imag](https://timsong-cpp.github.io/cppwp/n4861/complex.value.ops#itemdecl:2) overloads for complex numbers aren't addressable functions\.

What can we do about this? We can wrap the calls to these functions in a lambda:

```cpp
#ifndef SCI_CPLX_ORDER_SEP21
/* on abs() and arg() according to current practise */
const auto mostSignificant =
  [](std::complex<double> const &val) { return std::abs(val); };

const auto leastSignificant = 
  [](std::complex<double> const &val) { return std::arg(val); };
#else
/*  on real and imaginary parts as per SEP 21 recommendation.  */
const auto mostSignificant =
  [](std::complex<double> const &val) { return std::real(val); };

const auto leastSignificant =
  [](std::complex<double> const &val) { return std::imag(val); };
#endif
```

Although Scilab is compiled with the `-std=c++17` flag, preparing the codebase for migration to newer standards is highly recommended\.

**Snippet 6**

The PVS\-Studio warning: [V628](https://pvs-studio.com/en/docs/warnings/v628/) \[CWE\-670, CERT\-EXP19\-C\] It's possible that the line was commented out improperly, thus altering the program's operation logics\. LinkAdapter\.cpp 1140

```cpp
// delete all information related to the block
void LinkAdapter::remove_partial_links_information(ScicosID uid)
{
    auto it = partial_links.find(uid);
    if (it != partial_links.end())
       //DEBUG std::cerr << "erase " << uid << " partials " 
       //<< to_string(it->second) << "\n";
    partial_links.erase(uid);
}
```

The analyzer detected an issue where the code's formatting doesn't reflect the program's actual behavior\.

The `if` statement is missing braces, and there's a commented line required for debugging between the condition and the `erase` call\. Everything works as intended as long as it's commented: `erase` is called only if the element is found\. Otherwise, the debug statement is included in the condition body, and `erase` is always called\. This code is misleading\.

Out of curiosity, I checked the revision history to see what the code looked like before\. Originally, the member function looked like this:

```cpp
// delete all information related to the block
void LinkAdapter::remove_partial_links_information(ScicosID uid)
{
    partial_links.erase(uid);
}
```

Then, the search by key and debug output were added\.

We can make the code work as expected by simply adding braces\. We can also simplify the deletion process a bit:

```cpp
void LinkAdapter::remove_partial_links_information(ScicosID uid)
{
  auto it = partial_links.find(uid);
  if (it != partial_links.end())
  {
    //DEBUG std::cerr << "erase " << uid << " partials "
    // << to_string(it->second) << "\n";
    partial_links.erase(it);
  }
}
```

Now the `erase` member function immediately receives the iterator found using `find`; no extra search by key is performed\.

**Snippet 7**

The PVS\-Studio warning: [V502](https://pvs-studio.com/en/docs/warnings/v502/) \[CWE\-783, CERT\-EXP00\-C\] Perhaps the '?:' operator works in a different way than it was expected\. The '?:' operator has a lower priority than the '\=\=' operator\. sci\_sparse\.cpp 51

```cpp
types::Function::ReturnValue sci_sparse
  (types::typed_list &in, int _piRetCount, types::typed_list &out)
{
  bool isValid = true;
  // ....
  for (int i = 0 ; isValid && i < in.size() ; i++)
  {
    // ....
    case types::InternalType::ScilabBool :
    case types::InternalType::ScilabSparseBool :
    {
      isValid = (i == (in.size() > 1) ? 1 : 0);
    }
  // ....
}
```

Here's an amusing code snippet containing a precedence error that doesn't affect the result\. The conditional operator has lower precedence than the comparison operator, so the expression is parsed as follows: `(i == (in.size() > 1)) ? 1 : 0`\. First, the compiler compares `i` to the `in.size() > 1` result, then, it applies the conditional operator\. Perhaps the parentheses should've been placed differently:

```cpp
isValid = i == ((in.size() > 1) ? 1 : 0);
```

However, the result is the same anyway\. The curious thing is that the ternary operator doesn't change the value: the comparison result is already either `0` or `1`, so the operator is redundant regardless of how the parentheses are arranged, and `isValid` gets the same value\.

To avoid misleading developers, it's best to remove the unnecessary operation:

```cpp
isValid = i == (in.size() > 1);
```

### Typos and copypaste

**Snippet 8**

The PVS\-Studio warning: [V792](https://pvs-studio.com/en/docs/warnings/v792/) \[CWE\-691\] The 'isComplex' function located to the right of the operator '\|' will be called regardless of the value of the left operand\. Perhaps, it is better to use '\|\|'\. sci\_mesh2di\.cpp 42

```cpp
types::Function::ReturnValue sci_mesh2di
  (types::typed_list &in, int _iRetCount, types::typed_list &out)
{
  // ....  
  for (int i = 0; i < in.size(); i++)
  {
    if (!in[i]->isDouble() | in[i]->getAs<types::Double>()->isComplex())
    {
      Scierror(999, _
        ("%s: Wrong type for argument #%d: Real matrix expected.\n"), 
          "mesh2di", i);
      return types::Function::Error;
    }
  }
  // ....
}
```

The loop checks whether all input arguments are real, non\-complex numbers of the `Double` type\. However, it uses the bitwise `|` instead of the logical `||`\. The bitwise operator doesn't have a short\-circuit evaluation, so it always evaluates the right operand, even if the left operand has already established that the argument isn't a `Double`\.

The `getAs` function is implemented as `static_cast<T*>(this)` without any type checking:

```cpp
template<class T>
inline T* getAs(void)
{
   return static_cast<T*>(this);
}
```

Casting an object of a dynamic type that is neither a `Double` nor a subclass of a `Double` [results](https://timsong-cpp.github.io/cppwp/n4659/expr.static.cast#11) in undefined behavior\. Here's the fixed code:

```cpp
if (!in[i]->isDouble() || in[i]->getAs<types::Double>()->isComplex())
```

**Snippet 9**

The PVS\-Studio warning: [V501](https://pvs-studio.com/en/docs/warnings/v501/) \[CWE\-570\] There are identical sub\-expressions to the left and to the right of the '\!\=' operator: pDblx\-\>getSize\(\) \!\= pDblx\-\>getSize\(\) sci\_mesh2di\.cpp 52

```cpp
types::Function::ReturnValue sci_mesh2di
  (types::typed_list &in, int _iRetCount, types::typed_list &out)
{
  // ....
  types::Double *pDblx = in[0]->getAs<types::Double>();
  types::Double *pDbly = in[1]->getAs<types::Double>();

  if (pDblx->getSize() != pDblx->getSize())             // <=
  {
    Scierror(999, _("%s: Arguments #%d and #%d must have the same sizes.\n")
             , "mesh2di", 1,2);
    return types::Function::Error;
  }
  // ....
}
```

The function takes two arrays as input and checks whether they have the same size before proceeding\. If their sizes differ, it prints an error message and exits\. However, in the `pDblx->getSize() != pDblx->getSize()` condition, the code compares the `pDblx` size to itself\.

This is a classic copy\-paste typo\. The developers forgot to replace `pDblx` with `pDbly` in the second part of the condition\. The expression is always false, so the check never triggers\. This causes issues further in the code:

```cpp
int iNbNodes = pDblx->getSize();
// ....
for (int i=0; i < iNbNodes; i++)
{
  pDblxy->set(0,i,pDblx->get(i));
  pDblxy->set(1,i,pDbly->get(i));
}
```

If one array is shorter than the other, the loop goes out of bounds\. Instead of receiving a clear message, the user may encounter a crash, an incorrect result, or anything else at all, because the behavior in such a case is undefined\. Here's the fixed code:

```cpp
if (pDblx->getSize() != pDbly->getSize())
```

**Snippet 10**

The PVS\-Studio warning: [V517](https://pvs-studio.com/en/docs/warnings/v517/) \[CWE\-570, CERT\-MSC01\-C\] The use of 'if \(A\) \{\.\.\.\} else if \(A\) \{\.\.\.\}' pattern was detected\. There is a probability of logical error presence\. Check lines: 701, 785\. fromws\_c\.cpp 701

```cpp
typedef enum
{
  SCSREAL_N = 10,
  SCSCOMPLEX_N = 11,
  SCSINT_N = 80,
  SCSINT8_N = 81,
  SCSINT16_N = 82,
  SCSINT32_N = 84,
  SCSUINT_N = 800,
  SCSUINT8_N = 811,
  SCSUINT16_N = 812,
  SCSUINT32_N = 814,
  SCSUNKNOW_N = -1
} scicos_datatype_number;

SCICOS_BLOCKS_IMPEXP void fromws_c(scicos_block* block, int flag)
{
  //....
  else if (ytype == SCSINT32_N)
  {
    /* --------------------- int32 long ---------------------*/
    y_l = Getint32OutPortPtrs(block, 1);
    // ....
  }
  // ....
  else if (ytype == SCSINT32_N)
  {
    /* --------------------- uint32 ulong ---------------------*/
    y_ul = Getuint32OutPortPtrs(block, 1);
    // ....
  } 
  // ....
}
```

In a long chain of `if ... else if` statements, the `ytype` variable is compared to values of the `scicos_datatype_number` enumeration\. The analyzer detected that the `ytype == SCSINT32_N` condition appears twice, on lines 701 and 785\. The second check never executes\.

Judging by the comment in the second `uint32 ulong` branch, the `ytype == SCSUINT32_N` check should've been there\. The enumeration does contain this constant, and its value is 814\. This is another typical copy\-paste mistake: the developers copied the `int32` branch, changed its body, but forgot to update the condition\. As a result, the branch for `uint32` is missing\.

Here's the fixed code:

```cpp
else if (ytype == SCSUINT32_N)
```

**Snippet 11**

The PVS\-Studio warning: [V766](https://pvs-studio.com/en/docs/warnings/v766/) \[CWE\-462\] An item with the same key '"H5T\_VAX\_F64"' has already been added\. H5Type\.hxx 241

```cpp
static std::map<std::string, hid_t> initMap()
{
  std::map<std::string, hid_t> nameToType;
  // ....

  nameToType.insert
    (std::pair<std::string, hid_t>("H5T_IEEE_F64LE", H5T_IEEE_F64LE));
  nameToType.insert
    (std::pair<std::string, hid_t>("H5T_VAX_F32", H5T_VAX_F32));    // <=
  nameToType.insert
    (std::pair<std::string, hid_t>("H5T_VAX_F64", H5T_VAX_F64));    // <=
  nameToType.insert
    (std::pair<std::string, hid_t>("H5T_NATIVE_FLOAT", H5T_NATIVE_FLOAT));
  // ....
  nameToType.insert
    (std::pair<std::string, hid_t>("H5T_VAX_F32", H5T_VAX_F32));    // <=
  nameToType.insert
    (std::pair<std::string, hid_t>("H5T_VAX_F64", H5T_VAX_F64));    // <=
  nameToType.insert
    (std::pair<std::string, hid_t>("H5T_MIPS_F32", H5T_MIPS_F32));
  // ....
}
```

The `initMap` function populates a mapping table that associates string type names with their IDs\. The analyzer detected that the `"H5T_VAX_F32"` and `"H5T_VAX_F64"` pairs are added more than once\. The developers might have copied the same lines, accidentally adding them to the list twice\.

The duplicates are harmless for now because the values match\. However, if one of them contained a typo, then a value might have been omitted\. Manually finding such a mistake in 124 lines of code would take a lot of time\. Static analysis is really useful in situations like this\.

Here are the similar warnings:

* V766 \[CWE\-462\] An item with the same key '"H5T\_VAX\_F32"' has already been added\. H5Type\.hxx 240
* V766 \[CWE\-462\] An item with the same key 'L"mustBeMember"' has already been added\. arguments\.cpp 1098

**Snippet 12**

The PVS\-Studio warning: [V519](https://pvs-studio.com/en/docs/warnings/v519/) \[CWE\-563, CERT\-MSC13\-C\] The 'iy' variable is assigned values twice successively\. Perhaps this is a mistake\. Check lines: 53, 55\. int2db\.c 55

```cpp
int C2F(int2db)(int *n, int *dx, int *incx, double *dy, int *incy)
{
  int ix = 0, iy = 0;
  ....
  ix = 1;
  iy = 1;

  if (*incx < 0)
  {
      ix = (-(*n) + 1) * *incx + 1;
  }
  if (*incy < 0)
  {
      iy = (-(*n) + 1) * *incy + 1;
  }
  iy = (-(*n) + 1) * *incy + 1;
  ....
}
```

In the function, the `ix` and `iy` variables get the `1` value\. Then, if either `incx` or `incy` is negative, the corresponding index is recalculated using a formula\. Right after that, the same formula is applied again to `iy`, but this time without the condition\. This makes the `if (*incy < 0)` block pointless\. The extra line most likely got into the code by mistake and should be removed\.

It's curious that this error isn't new\. Looking through the commit history reveals that the extra line was present in earlier versions\. [At that time](https://gitlab.com/scilab/scilab/-/commit/cbccac2438e86151d1efad3d6856b95ebab2588a?file_path=scilab%2Fmodules%2Felementaries_functions%2Fsrc%2Fc%2Fint2db.c#ff7b269ee452d33aa4d612b134af9a2db610b25b), the conditions appeared on a single line, while the redundant assignment sat below them, indented as a part of the preceding `if` statement:

![1429_Scilab/image3.png](https://import.viva64.com/docx/blog/1429_Scilab/image3.png)

The developers [later](https://gitlab.com/scilab/scilab/-/commit/a846576255304dd81d6c449ecb577121c6454d94?file_path=scilab%2Fmodules%2Felementary_functions%2Fsrc%2Fc%2Fint2db.c#f25d9caab506dc369f265c3bdb3590cf92a0bcea) reformatted the code and added braces but didn't remove or replace the line:

![1429_Scilab/image4.png](https://import.viva64.com/docx/blog/1429_Scilab/image4.png)

This example shows that an error may go unnoticed for years, but it can be detected, for example, using static code analysis\.

### Those AI trainers

We recently published an article on our [blog](https://pvs-studio.com/en/blog/posts/) titled "[Bloated C\+\+ code](https://pvs-studio.com/en/blog/posts/cpp/1402/)," which covered an AI\-generated project\. Its main issue was code bloat\. AI\-generated code often contains lots of repetitive blocks and pointless checks\. While reviewing the Scilab analysis report, I got the impression that the AI model had learned from examples similar to those found in real\-world projects\. Here are some of them\.

**Snippet 13**

The PVS\-Studio warning: [V571](https://pvs-studio.com/en/docs/warnings/v571/) \[CWE\-571\] Recurring check\. The 'if \(m\_prob\_mem \!\= \_\_null\)' condition was already verified in line 80\. IDAManager\.hxx 82

```cpp
// ....
~IDAManager() {
  if (m_prob_mem != NULL)
  {
     if (m_prob_mem != NULL) IDAFree(&m_prob_mem);
      m_prob_mem = NULL;
  }
  ....
}
```

First, the program checks whether the `m_prob_mem` pointer is not null, and then repeats this check in the very next line\. But there's more: the `IDAFree` function contains another check for the same pointer:

```cpp
void IDAFree(void** ida_mem)
{
  IDAMem IDA_mem;

  if (*ida_mem == NULL) { return; }
  // ....
  free(*ida_mem);
  *ida_mem = NULL;
}
```

At the end of the function, the memory is released and the pointer is set to `NULL`, so we can replace the entire code with a single line:

```cpp
~IDAManager() {
  IDAFree(&m_prob_mem);
  // ....
}
```

**Snippet 14**

The PVS\-Studio warning: [V519](https://pvs-studio.com/en/docs/warnings/v519/) The 'tmp\-\>sn\_size' variable is assigned values twice successively\. Perhaps this is a mistake\. Check lines: 544, 550\. taucs\_scilab\.c 550

```cpp
static supernodal_frontal_matrix*
supernodal_frontal_create(int* firstcol_in_supernode,
                          int sn_size,
                          int n,
                          int* rowind)
{
  ....
  tmp->sn_size = sn_size;
  tmp->n = n;

  tmp->rowind = rowind;

  tmp->n = n;
  tmp->sn_size = sn_size;
  ....
}
```

Unless you've seen how things work in real projects, you might think that assigning a value just once is enough\. First, they assign the values one way, then they do it all over again in reverse\.

First, values are assigned to the `sn_size` and `n` data members, then to `rowind`\. Finally, the same values are assigned to `n` and `sn_size` a second time, but in reverse order\. The developers have to compare both blocks every time to make sure they're identical\.

**Snippet 15**

The PVS\-Studio warning: [V547](https://pvs-studio.com/en/docs/warnings/v547/) \[CWE\-570\] Expression 'i \>\= m\_iSize' is always false\. cell\.cpp 254

```cpp
Cell* Cell::set(InternalType** _pIT)
{
  // ....
  for (int i = 0; i < m_iSize; i++)
  {
    if (i >= m_iSize)
    {
      return NULL;
    }

    if (m_pRealData[i] != NULL)
  // ....
}
```

The `i < m_iSize` loop condition guarantees that the `i >= m_iSize` check within the loop will never execute\. The developers might have copied this check from the neighboring overload, `Cell::set(int _iIndex, InternalType* _pIT)`\. There, the index comes from outside the function, so the `_iIndex >= m_iSize` check prevents out\-of\-bounds access\. However, in this overload, the loop keeps the index within bounds, making the check redundant\. We can remove it to avoid confusing developers and cluttering the code\.

## Let's sum\-up

Static analysis helps detect errors that may have been lurking in a project for years\. You can check your own project using PVS\-Studio analyzer right now\. We've covered all the necessary steps—from installation to your first report—in the article "[Get started with PVS\-Studio static analyzer](https://pvs-studio.com/en/blog/posts/1358/)"\.


> \[Try PVS\\\-Studio for free\]\(https://pvs\-studio\.com/en/pvs\-studio/try\-free/\)