1. Лучший говнокод

    В номинации:
    За время:
  2. Си / Говнокод #3575

    +140

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    int 
    grub_auth_strcmp (const char *user_input, const char *template) 
    { 
      int ok = 1; 
      const char *ptr1, *ptr2; 
      for (ptr1 = user_input, ptr2 = template; *ptr1; ptr1++) 
        if (*ptr1 == (ptr2 ? *ptr2 : ptr1[1]) && ok && ptr2 != NULL) 
          ptr2++; 
        else 
          ok = 0; 
     
      return !ok; 
    }

    Несвежий говнокод (давно пропатчено) и, возможно, кто-то скажет "баян", однако оставлю это здесь.
    Код из загрузчика grub 1.97, проверка пароля. Принимает за верный пароль любую подстроку пароля.

    cfdev, 27 Июня 2010

    Комментарии (75)
  3. C# / Говнокод #299

    +1021.6

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    public static void brute(long diap)
    {
    n = 68491; //задаем некое число
    NewMessage("w8. Bruteforce working..."); //вызываем событие
    for (int i = 0; i < diap; i++) //мутим цикл
    {
    d = i;
    string brute = Convert.ToString(bug.Equals(n, d)); //сравниваем и возвращаем результат в строку
    if (brute == "True")
    {
    BruteComplete(d.ToString()); //вызываем событие при удачном переборе
    break;
    }
    }
    if (ok == false)
    {
    NewMessage("Brete Failed:(");
    }
    }

    Еще один:
    Данный говнокод взят из журнала "ХАКЕР". Вот ссылка, http://www.xakep.ru/magazine/xs/071/076/1.asp
    Тут программа должна подобрать число n. Как я понял тип n тут или не указан или переменная глобальная. Но нахрена тогда её объявлять глобальной если она применяется только в этом методе. Далее, d = i это вообще пиздец, да конечно же, если n это объект, а не int то все правильно. Но мне кажется автор полный мудак после того что создал строку brute, блять, конвертировал bool d string и сравнивает строку вида True с true. пиздец, пиздец....уебки...руки поотрывать...
    хакеры пля...=\

    guest, 28 Декабря 2008

    Комментарии (75)
  4. PHP / Говнокод #27506

    +3

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    $a != abs($a)
    $a+abs($a) == 0
    $a && !($a + abs($a))
    $n>>1 > $n
    substr_count($a,"-")
    is_nan(sqrt($number))
    is_nan(log($n))
    !array_shift(explode("-", $num))
    (int)$var === ~~(int)$var
    strlen(strval($num)) != strlen(strval(abs($num)))
    strlen(decbin($n)) == 32
    is_int(strpos(get_headers("http://habrahabr.ru/blogs/php/page$num/")[0], '404'));
    
    function lessThanZero ($num) {
        while (1) {
            if ($num++ == 0) {
                return true;
            }
        }
    }
    
    function is_value_between($value, $begin, $end) {
        return in_array($value, range($begin,$end));
    }

    "Как проверять отрицательное ли число ?
    В мануале в математических функциях не нашёл ."

    https://php.ru/forum/threads/kak-proverjat-otricatelnoe-li-chislo.8208/

    kezzyhko, 09 Июля 2021

    Комментарии (74)
  5. C++ / Говнокод #27486

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    // https://code.qt.io/cgit/qt/qtbase.git/tree/src/corelib/global/qglobal.h?h=v5.13.1#n1017
    
    #if __cplusplus >= 201703L
    // Use C++17 if statement with initializer. User's code ends up in a else so
    // scoping of different ifs is not broken
    #define Q_FOREACH(variable, container)                                   \
    for (auto _container_ = QtPrivate::qMakeForeachContainer(container);     \
         _container_.i != _container_.e;  ++_container_.i)                   \
        if (variable = *_container_.i; false) {} else
    #else
    // Explanation of the control word:
    //  - it's initialized to 1
    //  - that means both the inner and outer loops start
    //  - if there were no breaks, at the end of the inner loop, it's set to 0, which
    //    causes it to exit (the inner loop is run exactly once)
    //  - at the end of the outer loop, it's inverted, so it becomes 1 again, allowing
    //    the outer loop to continue executing
    //  - if there was a break inside the inner loop, it will exit with control still
    //    set to 1; in that case, the outer loop will invert it to 0 and will exit too
    #define Q_FOREACH(variable, container)                                \
    for (auto _container_ = QtPrivate::qMakeForeachContainer(container); \
         _container_.control && _container_.i != _container_.e;         \
         ++_container_.i, _container_.control ^= 1)                     \
        for (variable = *_container_.i; _container_.control; _container_.control = 0)
    #endif

    А можно ли свой foreach сделать через какую-нибудь шаблонопарашу? Или тут, как обычно, нужна гомоиконность?

    j123123, 28 Июня 2021

    Комментарии (74)
  6. PHP / Говнокод #26748

    0

    1. 1
    https://webmakaka.ru/

    https://webmakaka.ru/

    MAKAKA, 09 Июня 2020

    Комментарии (74)
  7. JavaScript / Говнокод #26622

    +1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    (() => {
    const urlPrefix = 'https://distrochooser.de/en/';
    const msgs = [];
    let msg = '';
    for (let i = 479076; i > 0; --i) {
    const url = urlPrefix + i;
    if (msg.length + url.length + 1 < 2000) {
    msg += '\n';
    msg += url;
    } else {
    msgs.push(msg);
    msg = url;
    }
    }
    return msgs;
    })()

    Проходим мимо, не обращаем внимания.

    Ведутся SEO-работы.

    Needless, 30 Апреля 2020

    Комментарии (74)
  8. Куча / Говнокод #25663

    +2

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    https://habr.com/ru/post/219685/
    |
    ->
    Плохо выразился. В старых не надо объявлять поле типа Pointer, в старых объявляется поле интерфейсного типа, а при присвоении ему значения делается приведение: Pointer(FInterfaceField) := Pointer(InterfaceVariable);
    Так делали, чтобы получить weak-ссылку и при этом не заниматься многочисленными приведением Pointer к интерфейсу.
    Не будет никакого AV, если вы руками присвоите nil в деструкторе, тоже через приведение к Pointer.

    Ох, лол...

    cmepmop, 05 Июня 2019

    Комментарии (74)
  9. C++ / Говнокод #23449

    0

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    16. 16
    17. 17
    18. 18
    19. 19
    20. 20
    21. 21
    22. 22
    23. 23
    24. 24
    25. 25
    26. 26
    27. 27
    28. 28
    29. 29
    30. 30
    31. 31
    32. 32
    33. 33
    34. 34
    35. 35
    36. 36
    37. 37
    38. 38
    39. 39
    40. 40
    41. 41
    42. 42
    43. 43
    44. 44
    45. 45
    46. 46
    47. 47
    48. 48
    49. 49
    50. 50
    51. 51
    52. 52
    53. 53
    54. 54
    https://github.com/TartanLlama/optional/blob/master/optional.hpp#L853
    
      /// Constructs the stored value with `u`.
      /// \synopsis template <class U=T> constexpr optional(U &&u);
      template <
          class U = T,
          detail::enable_if_t<std::is_convertible<U &&, T>::value> * = nullptr,
          detail::enable_forward_value<T, U> * = nullptr>
      constexpr optional(U &&u) : base(in_place, std::forward<U>(u)) {}
    
      /// \exclude
      template <
          class U = T,
          detail::enable_if_t<!std::is_convertible<U &&, T>::value> * = nullptr,
          detail::enable_forward_value<T, U> * = nullptr>
      constexpr explicit optional(U &&u) : base(in_place, std::forward<U>(u)) {}
    
      /// Converting copy constructor.
      /// \synopsis template <class U> optional(const optional<U> &rhs);
      template <
          class U, detail::enable_from_other<T, U, const U &> * = nullptr,
          detail::enable_if_t<std::is_convertible<const U &, T>::value> * = nullptr>
      optional(const optional<U> &rhs) {
        this->m_has_value = true;
        new (std::addressof(this->m_value)) T(*rhs);
      }
    
      /// \exclude
      template <class U, detail::enable_from_other<T, U, const U &> * = nullptr,
                detail::enable_if_t<!std::is_convertible<const U &, T>::value> * =
                    nullptr>
      explicit optional(const optional<U> &rhs) {
        this->m_has_value = true;
        new (std::addressof(this->m_value)) T(*rhs);
      }
    
      /// Converting move constructor.
      /// \synopsis template <class U> optional(optional<U> &&rhs);
      template <
          class U, detail::enable_from_other<T, U, U &&> * = nullptr,
          detail::enable_if_t<std::is_convertible<U &&, T>::value> * = nullptr>
      optional(optional<U> &&rhs) {
        this->m_has_value = true;
        new (std::addressof(this->m_value)) T(std::move(*rhs));
      }
    
      /// \exclude
      template <
          class U, detail::enable_from_other<T, U, U &&> * = nullptr,
          detail::enable_if_t<!std::is_convertible<U &&, T>::value> * = nullptr>
      explicit optional(optional<U> &&rhs) {
        this->m_has_value = true;
        new (std::addressof(this->m_value)) T(std::move(*rhs));
      }

    Я даже не знаю, какой конкретно фрагмент этого творчества сюда выкладывать.

    https://github.com/TartanLlama/optional C++11/14/17 std::optional with functional-style extensions https://optional.tartanllama.xyz

    Вообще меня это забавляет, все эти костылепостроения поверх плюсов. Сделайте там уже возможность в компилтайме работать напрямую с исходным кодом самого себя, т.е. чтобы был некий код, который плюсокомпилятором в компилтайме обрабатывался, и чтобы он принимал исходник самого себя просто в виде тупо текста, и мог произвольно менять содержимое исходника на этапе компиляции (не меняя при этом сами файлы в файловой системе), и чтоб в качестве библиотек к этому компилтайм-метушению шел лексер-парсер плюсов.

    Понятно что из плюсов никакого гомоиконного лиспа сделать не выйдет, ведь тогда надо выкинуть очень красивый и элегантный плюсосинтаксис вида std::kukarek(std:kudah<std:kokoko{kokoko ko[hui<govno>]}>:()[*huita]{}) и заменить его на бездуховные скобочки

    j123123, 24 Октября 2017

    Комментарии (74)
  10. C# / Говнокод #19533

    −1

    1. 01
    2. 02
    3. 03
    4. 04
    5. 05
    6. 06
    7. 07
    8. 08
    9. 09
    10. 10
    11. 11
    12. 12
    13. 13
    14. 14
    15. 15
    if (p != null)
    {
        Thread thread = new Thread(() =>
        {
            StaffList.App.Controls.Personal.PersonRec rec = new Controls.Personal.PersonRec();
            rec.DataContext = p;
            rec.Mode = StaffList.Controls.OperatingMode.Show;
            var win = new BaseWindow();
            win.Form = rec;
            win.ShowDialog();
        });
    
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
    }

    Это мы так делаем немодальные окна.

    kerman, 25 Февраля 2016

    Комментарии (74)
  11. bash / Говнокод #18532

    −704

    1. 1
    test "$(whoami)" != 'root' && (echo you are using a non-privileged account; exit 1)

    Real Programmers
    Most programmers will prefer to use the test built-in command, which is equivalent to using square brackets for comparison, like this

    http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html#sect_07_01_02_03

    Вот такие они, real programmers.
    Подсказка: Круглые скобки в шелле запускают саб-шелл

    Elvenfighter, 26 Июля 2015

    Комментарии (74)