1. Си / Говнокод #15638

    +134

    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
    
    /* A C statement or statements which output an assembler instruction
       opcode to the stdio stream STREAM.  The macro-operand PTR is a
       variable of type `char *' which points to the opcode name in its
       "internal" form--the form that is written in the machine description.
    
       GAS version 1.38.1 doesn't understand the `repz' opcode mnemonic.
       So use `repe' instead.  */
    
    #undef ASM_OUTPUT_OPCODE
    #define ASM_OUTPUT_OPCODE(STREAM, PTR)	\
    {									\
      if ((PTR)[0] == 'r'							\
          && (PTR)[1] == 'e'						\
          && (PTR)[2] == 'p')						\
        {									\
          if ((PTR)[3] == 'z')						\
    	{								\
    	  fputs ("repe", (STREAM));					\
    	  (PTR) += 4;							\
    	}								\
          else if ((PTR)[3] == 'n' && (PTR)[4] == 'z')			\
    	{								\
    	  fputs ("repne", (STREAM));					\
    	  (PTR) += 5;							\
    	}								\
        }									\
      else									\
        ASM_OUTPUT_AVX_PREFIX ((STREAM), (PTR));				\
    }

    Костыль из GCC. Ассемблер GAS версии 1.38.1 не переваривает мнемоники repz и repnz. Эта макрохрень перекодирует их в repe и repne соответственно
    https://github.com/mirrors/gcc/blob/master/gcc/config/i386/gas.h#L81

    j123123, 02 Апреля 2014

    Комментарии (1)
  2. Си / Говнокод #15628

    +136

    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
    #include <stdio.h>
    #include <inttypes.h>
    
    inline uint8_t mid_ch (uint8_t a, uint8_t b, uint8_t res)
    {
      if (b == 0){ if (a >= 2) return mid_ch (a-2, b  , res+1); else return res;}
      if (a == 0){ if (b >= 2) return mid_ch (a  , b-2, res+1); else return res;}
      return mid_ch (a-1, b-1, res+1);
    }
    
    uint64_t mid_0_ch (uint64_t a, uint64_t b)
    {
      return mid_ch(a, b, 0);
    }
    
    
    int main(void)
    {
      printf("%u %u", mid_0_ch (253, 123), (253+123)/2);
      return 0;
    }

    Нахождение среднего арифметического двух чисел через рекурсию. Сначала сделал для uint64_t чтобы это имело смысл, ведь сложение двух 64-битных чисел с записью результата в третье может привести к целочисленному переполнению (для 64-битных чисел, сложение которых может привести к переполнению, этот код работал чрезвычайно медленно, поэтому я ограничился 8-битными). При таком наркоманско-рекурсивном алгоритме этого переполнения не будет. 128-битные типы есть только как нестандартное расширение, но тогда еще возникает вопрос, как найди среднее арифметическое двух таких 128-битных чисел? А если есть 256-битные, то как тогда их них находить среднеарифметическое... ну и так далее.
    Можно эту проблему еще решать через битовые маски т.е. убрать из обеих чисел самые старшие биты (предварительно сохранив их), сложить эти два числа, поделить на два, потом уже эти сохраненные биты вида 10000... или 0000... оба поделить на 2(сдвинуть на один разряд) и прибавить. Наркоманство какое-то.
    Почему бы не сделать в С некий особый целочисленный тип, в котором любая фигня влезет, но который бы использовался только временно для промежуточных вычислений, чтобы не делать бэкапы битиков всяких?

    j123123, 31 Марта 2014

    Комментарии (22)
  3. Си / Говнокод #15588

    +129

    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
    int minus(int ch)
    {
    if (ch < 0)
    {
    char buf[255];
    char *chs = itoa(ch);
    char *chsn = (char*)calloc(1, strlen(chs)+1];
    memset(chsn, 0, strlen(chs)+1);
    chsn[0] = '-';
    for (int i = 1, int j = 0; j < strlen(chs); i++, j++)
    {
    chsn[i] = chs[j];
    }
    int ret = atoi(chsn);
    return ret;
    }
    else
    {
    char buf[255];
    char *chs = itoa(ch);
    char *chsn = (char*)calloc(1, strlen(chs)+1];
    memset(chsn, 0, strlen(chs)+1);
    for (int i = 1, int j = 0; i < strlen(chs); i++, j++)
    {
    chsn[j] = chs[i];
    }
    int ret = atoi(chsn);
    return ret;
    }
    }

    gost, 27 Марта 2014

    Комментарии (7)
  4. Си / Говнокод #15576

    +133

    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
    55. 55
    56. 56
    57. 57
    58. 58
    59. 59
    60. 60
    61. 61
    62. 62
    63. 63
    64. 64
    65. 65
    66. 66
    67. 67
    68. 68
    69. 69
    70. 70
    71. 71
    72. 72
    73. 73
    74. 74
    75. 75
    76. 76
    77. 77
    78. 78
    79. 79
    80. 80
    81. 81
    82. 82
    83. 83
    84. 84
    85. 85
    86. 86
    87. 87
    FRebuildSubdocPlcpcd(pdsr, ddsr, edcDrp)
    struct DSR *pdsr;
    int ddsr;
    int edcDrp;
    {
    /* we pull some tricks here because the normal editing situation doesn't cover
    	what we're trying to do:
    		1. We don't disturb the old chEop at the end of the subdoc until after
    			we have replaced the old pieces with the new one; then we delete it
    			surgically (we know it has either a different fn or noncontiguous
    			fc from the new stuff -- so just subtract ccpEop from cpMac and
    			remove the last pcd entry)
    		2. The plcfnd/plchdd needn't take part in the editing, since the CP
    			bounds will be the same after as they were before, and in fact
    			AdjustCp doesn't know how to handle editing the subdoc data -- so
    			we hide the plc from the editing
    */
    	int doc = pdsr->doc;
    	int docSubdoc;
    	int ipcd;
    	CP ccpSubdoc;
    
    	struct DOD *pdod;
    	struct PLC **hplcfnd;
    	struct PLC **hplcfld;
    	struct DRP *pdrp;
    	struct CA ca1, ca2;
    	struct PLC **hplcpcd, **hplcpcdSub;
    	CP *pccpSubdoc;
    	struct PCD pcd;
    
    	/*  momentarily break link to subdoc doc in dod so that ReplaceCps
    		doesn't get confused. */
    	pdrp = ((int *)PdodDoc(doc)) + edcDrp;
    	docSubdoc = pdrp->doc;
    	pccpSubdoc = ((int *)pdsr) + ddsr;
    	ccpSubdoc = *pccpSubdoc;
    	pdrp->doc = docNil;
    
    	if (docSubdoc != docNil && ccpSubdoc != cp0)
    		{
    		/* hide the subdoc plcfnd */
    		pdod = PdodDoc(docSubdoc);
    		hplcfnd = pdod->hplcfnd;
    		hplcfld = pdod->hplcfld;
    		pdod->hplcfnd = hNil;
    		pdod->hplcfld = hNil;
    
    		/* replace original piece table for subdoc with new --
    			note that we leave the chEop at end temporarily */
    		ccpSubdoc -= ccpEop;
    		if (!FReplaceCps(PcaSet(&ca1, docSubdoc, cp0, ccpSubdoc),
    				PcaSet(&ca2, doc, pdsr->ccpText, pdsr->ccpText + ccpSubdoc)))
    			return fFalse; 
    
    		/* now replace the PCD for the chEop left over from olden times;
    		   unfortunately, the editing routines can't do this for us */
    		hplcpcd = PdodDoc(doc)->hplcpcd;
    		if ((ipcd = IpcdSplit(hplcpcd, pdsr->ccpText + ccpSubdoc)) == iNil)
    			return fFalse;
    		GetPlc(hplcpcd, ipcd, &pcd);
    		hplcpcdSub = PdodDoc(docSubdoc)->hplcpcd;
    		PutPlc(hplcpcdSub, IMacPlc(hplcpcdSub) - 1, &pcd);
    		if ((ipcd = IpcdSplit(hplcpcdSub, ccpSubdoc+ccpEop)) == iNil)
    			return fFalse;
    		PutPlc(hplcpcdSub, ipcd-1, &pcd);
    
    		/* eliminate the footnote/header text from the main doc */
    		ca2.cpLim += ccpEop;
    		if (!FDelete(&ca2))
    			return fFalse;
    		pdod = PdodDoc(docSubdoc);
    
    		/* restore plcfnd */
    		pdod->hplcfnd = hplcfnd;
    		pdod->hplcfld = hplcfld;
    		pdod->fDirty = fFalse;
    
    		TruncateAllSels(docSubdoc, pdod->cpMac);
    		}
    
    	/* restore docFtn/docHdr */
    	pdrp = ((int *)PdodDoc(doc)) + edcDrp;
    	pdrp->doc = docSubdoc;
    
    	return fTrue;
    }

    Word for Windows 1.1a. 17 мегабайт отборного говнокода.

    http://habrahabr.ru/post/217081/

    gost, 26 Марта 2014

    Комментарии (7)
  5. Си / Говнокод #15572

    +131

    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
    #ifndef _AVRECORD_H__INCLUDED_
    #define _AVRECORD_H__INCLUDED_
    #include 
    
    //! Структура сигнатуры
    typedef struct SAVSignature{
    SAVSignature(){
    this->Offset = 0;
    this->Lenght = 0;
    memset(this->Hash, 0, sizeof(this->Hash));
    }
    DWORD Offset; // - Смещение файле
    DWORD Hash[4]; // - MD5 хэш
    DWORD Lenght; // - Размер данных
    } * PSAVSignature;
    
    //! Структура записи о зловреде
    typedef struct SAVRecord{
    SAVRecord(){
    this->Name = NULL;
    this->NameLen = 0;
    }
    ~SAVRecord(){
    if(this->Name != NULL) this->Name;
    }
    //! Выделение памяти под имя
    void allocName(BYTE NameLen){
    if(this->Name == NULL){
    this->NameLen = NameLen;
    this->Name = new CHAR[this->NameLen + 1];
    memset(this->Name, 0, this->NameLen + 1);
    }
    }
    PSTR Name; // - Имя
    BYTE NameLen; // - Размер имени
    SAVSignature Signature; // - Сигнатура
    
    } * PSAVRecord;
    
    #endif

    Пишем антивирус на аццкой помеси Си, ООП-стайла, говнокода и синтаксических ошибок.
    http://hack-academy.ru/programming/system/361-pishem-svoj-antivirus-na-c.html

    gost, 25 Марта 2014

    Комментарии (25)
  6. Си / Говнокод #15540

    +142

    1. 1
    2. 2
    3. 3
    4. 4
    5. 5
    6. 6
    for(int i=0; i<10; i++) {
      if(i==5) {
        //do something
        break;
      }
    }

    Без слов... Взято из реального проекта, с некоторыми упрощениями

    dm-ua, 20 Марта 2014

    Комментарии (7)
  7. Си / Говнокод #15510

    +143

    1. 1
    strlen(s + 5);

    "А чего это оно на 10 символов меньше чем надо возвращает?"

    bormand, 18 Марта 2014

    Комментарии (75)
  8. Си / Говнокод #15487

    +133

    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
    if (other && other->client && other->s.number < MAX_CLIENTS)
    		{//player touched me
    			/*
    			char *text;
    			qboolean	keyTaken;
    			//give him my key
                            ...
    
    			*/
    			//rwwFIXMEFIXME: support for goodie/security keys?
    			/*
    			if ( keyTaken )
    			{//remove my key
    				NPC_SetSurfaceOnOff( self, "l_arm_key", 0x00000002 );
    				self->message = NULL;
    				//FIXME: temp pickup sound
    				G_Sound( player, G_SoundIndex( "sound/weapons/key_pkup.wav" ) );
    				//FIXME: need some event to pass to cgame for sound/graphic/message?
    			}
    			//FIXME: temp message
    			gi.SendServerCommand( NULL, text );
    			*/
    		}

    FIXMEFIXMEFIXME... Да ну нахуй, лучше все закомментим.

    gost, 15 Марта 2014

    Комментарии (38)
  9. Си / Говнокод #15447

    +134

    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
    55. 55
    56. 56
    57. 57
    58. 58
    59. 59
    60. 60
    61. 61
    62. 62
    63. 63
    64. 64
    65. 65
    66. 66
    67. 67
    68. 68
    #include <stdio.h>
    #define max(x,y) ((x>y)?x:y)
    #define N 255
    typedef unsigned char uchar;
    
    uchar s,t,x,y,z,n,S[10000],FO[N+N*(N-1)/2];
    uchar mask[]={1,2,4,8,16,32,64,128};
    int TOP=0;
    unsigned int COUNTER=0,AO[N];
    FILE *in;
    
    int pop(){
    //if the top element in the stack is passed and stack is not empty,
    //find next parent vertex
    while(S[TOP]>128 && TOP>0) TOP-=S[TOP]-128;
    return(TOP);
    }
    
    int push(){		//add new elements to the stack
    int tmp=TOP,i,j,k;		//tmp is a temporary variable 
    x=S[TOP-S[TOP]+1];	//x is a parent vertex
    for(i=1;i<=FO[AO[x]];i++){
       y=FO[AO[x]+i];	//y is a neigbour of x 
       if(!test(y)){	//y is visited? if not keep going
         k=max(y/8+1,S[TOP]-2);	//copy set P(x) to the new set P(y)
         S[++tmp]=y;
         for(j=0;j<k;j++,S[++tmp]=0);
         S[++tmp]=k+2;
         for(j=1;j<=S[TOP]-2;j++) S[tmp-j]=S[TOP-j];
         S[tmp-(y/8+1)]|=mask[y-(y/8)*8];	//add child y to P(y)
       }
    }
    S[TOP]+=128;	//drop flag for the vertex x
    TOP=tmp;	//the last child y become parent
    }
    
    int test(int j){	//does vertex j in the set P(TOP)?
    z=((j/8+1)>S[TOP]-2)?0:(S[TOP-(j/8+1)] & mask[j-(j/8)*8])?1:0;
    return(z);
    }
    
    int inc(){	//the path was found
    COUNTER++;
    S[TOP]+=128;
    }
    
    int main(){
    int i,j,k;
    in=fopen("Data15.txt","r");	//open file
    fscanf(in," %d %d",&i,&n);		//read the number of vertices
    for(k=n,i=0;k>=0;k--){
       fscanf(in,"%d %d",&j,&FO[i]);
       j=FO[i];
       for(AO[n-k]=++i-1;j>0;j--,i++){
          fscanf(in,"%d ",&FO[i]);
       }
    }
    printf("Type first and end nodes: ");	//type s and t separated by space
    scanf("%d %d",&s,&t);
    S[0]=s;
    for(j=1;j<=s/8+1;S[j++]=0);
    S[j]=s/8+3;
    TOP=j;
    S[TOP-(s/8+1)]|=mask[s-(s/8)*8];
    while(pop()>=0) (test(s) && test(t))?inc():push(); //launch breadth-search algorithm
    printf("# of paths in the graph b/w s=%d and t=%d equals %d\n",s,t,COUNTER);
    return(0);
    }

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

    прога подсчитывает полное число путей в графе между заданными вершинами s и t.
    граф считывается из файла в формате: "номер_вершины степень_вершины {достижимые_вершины_через_пробел}"
    (по коду видно)

    govnyuk, 13 Марта 2014

    Комментарии (15)
  10. Си / Говнокод #15406

    +142

    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
    55. 55
    static char months [] = "JanFebMarAprMayJunJulAugSepOctNovDecGlk";
    static char dows [] = "SunMonTueWedThuFriSatEar";
    
    
    int dd [] =
    {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    
    void gen_http_date (char date_buffer[29], int time) {
      int day, mon, year, hour, min, sec, xd, i, dow;
      if (time < 0) time = 0;
      sec = time % 60;
      time /= 60;
      min = time % 60;
      time /= 60;
      hour = time % 24;
      time /= 24;
      dow = (time + 4) % 7;
      xd = time % (365 * 3 + 366);
      time /= (365 * 3 + 366);
      year = time * 4 + 1970;
      if (xd >= 365) {
        year++;
        xd -= 365;
        if (xd >= 365) {
          year++;
          xd -= 365;
          if (xd >= 366) {
            year++;
            xd -= 366;
          }
        }
      }
      if (year & 3) {
        dd[1] = 28;
      } else {
        dd[1] = 29;
      }
    
      for (i = 0; i < 12; i++) {
        if (xd < dd[i]) {
          break;
        }
        xd -= dd[i];
      }
    
      day = xd + 1;
      mon = i;
      assert (day >= 1 && day <= 31 && mon >=0 && mon <= 11 &&
          year >= 1970 && year <= 2039);
    
      sprintf (date_buffer, "%.3s, %.2d %.3s %d %.2d:%.2d:%.2d GM",
          dows + dow * 3, day, months + mon * 3, year,
          hour, min, sec);
      date_buffer[28] = 'T';
    }

    Делать имена месяцев и дни недели одной сишной строкой, чтобы потом выводить оттуда по три символа через sprintf, считая оффсет умножением на 3 т.к. имена месяцев и дней недели влазят в три символа
    https://github.com/vk-com/kphp-kdb/blob/ce1ac4fbde2d3b546936ad07d6a748958f6d2198/net/net-http-server.c#L664

    http://roem.ru/2013/07/20/kphp76561/
    >ВКонтактовские "олимпиадники"-чемпионы ACM разработали крайне интересную высоконагруженным сайтам технологию.

    Хреновые какие-то олимпиадники попались, раз неосилили http://ideone.com/IfvBgi

    j123123, 09 Марта 2014

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