[Программирование, .NET, C#] C# Programmer, It's Time to Test Yourself and Find Error
Автор
Сообщение
news_bot ®
Стаж: 6 лет 9 месяцев
Сообщений: 27286
The PVS-Studio analyzer is regularly updated with new diagnostic rules. Curiously enough, diagnostics often detect suspicious code fragments before the end of the work. For example, such a situation may happen while testing on open-source projects. So, let's take a look at one of these interesting finding.
As mentioned earlier, one of the stages of diagnostic rule testing is to check its operation on a real codebase. To that end, we have a set of selected open-source projects that we use for the analysis. The obvious advantage of this approach is the ability to see the diagnostic rule behavior in real conditions. There's also a less obvious advantage. Sometimes you may find such an interesting case, so it would be a sin not to write an article about it. :)Now, let's take a look at the code from the Bouncy Castle C# project and find the error in it:
public static string ToString(object[] a)
{
StringBuilder sb = new StringBuilder('[');
if (a.Length > 0)
{
sb.Append(a[0]);
for (int index = 1; index < a.Length; ++index)
{
sb.Append(", ").Append(a[index]);
}
}
sb.Append(']');
return sb.ToString();
}
For those who like to cheat and peek, I added a picture to keep you guessing.
I'm sure some of you couldn't see the error without using the IDE or the StringBuilder class documentation. The error happened when calling the constructor:
StringBuilder sb = new StringBuilder('[');
Actually, this is exactly what the PVS-Studio static analyzer warns us about: V3165 Character literal '[' is passed as an argument of the 'Int32' type whereas similar overload with the string parameter exists. Perhaps, a string literal should be used instead. Arrays.cs 193.The programmer wanted to create an instance of the StringBuilder type, where the string begins with the '[' character. However, due to a typo, we'll have an object without any characters with a capacity of 91 elements.This happened because the programmer used single quotes instead of double-quotes. That's why the wrong constructor overload was called:
....
public StringBuilder(int capacity);
public StringBuilder(string? value);
....
When the constructor is called, the '[' character literal will be implicitly cast to the corresponding value of the int type (91 in Unicode). Because of this, the constructor with the int type parameter setting the initial capacity will be called. Although, the programmer wanted to call the constructor which sets the string's beginning.To fix the error, the developer has to replace the character literal with a string literal (i.e., use "[" instead of '['). It will cause the correct constructor overload.We decided to go the extra mile and expanded the cases reviewed by diagnostic. As a result, in addition to character literals, some other expressions of the char type are considered now. We also check methods in the same way. The diagnostic described above was added in the PVS-Studio 7.11 release. You can download the analyzer latest version yourself. You'll see what the V3165 diagnostic can do, as well as other diagnostics for C, C++, C#, and Java.By the way, the users themselves often suggest some ideas of diagnostics to us. This time it has happened thanks to the user of Krypt from Habr. If you also have some ideas for diagnostic rules - don't hesitate to reach out to us!P.S. This error has already been fixed in the current project code base. Though, this doesn't change the fact that it has existed in the code for some time, and that static analysis allows you to identify such problems and fix them at the earliest stages.
===========
Источник:
habr.com
===========
Похожие новости:
- [Python, Программирование, Алгоритмы, Машинное обучение, Искусственный интеллект] Собираем нейросети. Классификатор животных из мультфильмов. Без данных и за 5 минут. CLIP: Обучение без Обучения + код
- [Программирование, Функциональное программирование, Софт] С добавлением лямбда-функций язык программирования Excel стал полным по Тьюрингу
- [Разработка под iOS, Разработка мобильных приложений, Разработка под Android, C#, Xamarin] Использование сервисов и обработка их результатов в Xamarin
- [Программирование, C++, C#, Карьера в IT-индустрии] Наблюдения за «погодными условиями» в проекте с C++/CLI
- [Программирование, Карьера в IT-индустрии] Плюсы профессии программиста, что нравится в работе программистом
- [Программирование, Карьера в IT-индустрии] Минусы профессии программиста, что не нравится в работе
- [Программирование, Карьера в IT-индустрии] Советы начинающим разработчикам
- [Программирование, Алгоритмы, Компиляторы] Клонированные переменные
- [Разработка игр, C#, Unity, Дизайн игр] Эффект дождя. Частицы в Unity 3D
- [Программирование, Java, Scala, Функциональное программирование] Еще раз про try и Try
Теги для поиска: #_programmirovanie (Программирование), #_.net, #_c#, #_pvs, #_pvsstudio, #_csharp, #_blog_kompanii_pvsstudio (
Блог компании PVS-Studio
), #_programmirovanie (
Программирование
), #_.net, #_c#
Вы не можете начинать темы
Вы не можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете голосовать в опросах
Вы не можете прикреплять файлы к сообщениям
Вы не можете скачивать файлы
Текущее время: 22-Ноя 17:52
Часовой пояс: UTC + 5
Автор | Сообщение |
---|---|
news_bot ®
Стаж: 6 лет 9 месяцев |
|
The PVS-Studio analyzer is regularly updated with new diagnostic rules. Curiously enough, diagnostics often detect suspicious code fragments before the end of the work. For example, such a situation may happen while testing on open-source projects. So, let's take a look at one of these interesting finding. As mentioned earlier, one of the stages of diagnostic rule testing is to check its operation on a real codebase. To that end, we have a set of selected open-source projects that we use for the analysis. The obvious advantage of this approach is the ability to see the diagnostic rule behavior in real conditions. There's also a less obvious advantage. Sometimes you may find such an interesting case, so it would be a sin not to write an article about it. :)Now, let's take a look at the code from the Bouncy Castle C# project and find the error in it: public static string ToString(object[] a)
{ StringBuilder sb = new StringBuilder('['); if (a.Length > 0) { sb.Append(a[0]); for (int index = 1; index < a.Length; ++index) { sb.Append(", ").Append(a[index]); } } sb.Append(']'); return sb.ToString(); } I'm sure some of you couldn't see the error without using the IDE or the StringBuilder class documentation. The error happened when calling the constructor: StringBuilder sb = new StringBuilder('[');
....
public StringBuilder(int capacity); public StringBuilder(string? value); .... =========== Источник: habr.com =========== Похожие новости:
Блог компании PVS-Studio ), #_programmirovanie ( Программирование ), #_.net, #_c# |
|
Вы не можете начинать темы
Вы не можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете голосовать в опросах
Вы не можете прикреплять файлы к сообщениям
Вы не можете скачивать файлы
Вы не можете отвечать на сообщения
Вы не можете редактировать свои сообщения
Вы не можете удалять свои сообщения
Вы не можете голосовать в опросах
Вы не можете прикреплять файлы к сообщениям
Вы не можете скачивать файлы
Текущее время: 22-Ноя 17:52
Часовой пояс: UTC + 5