├── .gitignore ├── README.md ├── hello.sh ├── interestingness ├── README.md ├── astyle_example │ ├── bad_code.c │ └── good_code.c ├── colors.c ├── epsilon │ ├── Readme.md │ └── epsilon_example.cpp ├── float_error.c ├── hack_const.c ├── mem.c ├── preprocessor.c ├── sum.c └── wow_i++.c ├── lectures ├── 08-11-18-lecture │ ├── 2dim_array.c │ ├── enum.c │ ├── struct.c │ └── union.c ├── 17oct22_read_unlim_str │ └── main.c ├── 19-04-21-lec │ └── README.md ├── README.md ├── arrayStack.c ├── bmp │ ├── bmp.c │ ├── image.bmp │ ├── out.bmp │ └── simpsonsvr.bmp ├── cpp_string_sort │ ├── 1.cpp │ ├── 2.cpp │ └── 3.cpp ├── cw_examples.c ├── dir_files │ ├── f1 │ │ ├── f2 │ │ │ └── test-0003.txt │ │ └── test-0002.txt │ ├── main.c │ ├── test-0001.txt │ └── test-0002.txt ├── doxygen │ ├── Doxyfile │ └── stack.h ├── exeptions.cpp ├── find_regex │ ├── .maker.sh.swp │ ├── Makefile │ ├── answer │ └── generator.sh ├── function_pointers │ ├── example1.c │ ├── example2.c │ └── example3.c ├── getopt │ ├── getopt.c │ └── getopt_long.c ├── hashtable.c ├── libc │ ├── Makefile │ ├── assert.c │ ├── complex.c │ ├── errno.c │ ├── fenv.c │ ├── float.c │ ├── iso646.c │ ├── locale.c │ ├── math.c │ ├── setjmp.c │ ├── signal.c │ ├── stdarg.c │ ├── stdbool.c │ ├── stddef.c │ ├── stdint.c │ ├── stdlib.c │ ├── string.c │ ├── tgmath.c │ ├── time.c │ └── wchar.c ├── list │ ├── list.cpp │ ├── list_lect.c │ ├── list_swap.c │ ├── list_swap.cpp │ └── list_swap1.c ├── list_22_march_21.c ├── list_based_stack.c ├── mim_ssprintscan.c ├── multidim_arrays │ ├── ex1.c │ ├── ex2.c │ ├── ex3.c │ ├── ex4.c │ └── ex5.c ├── numStorage.c ├── num_storage │ ├── Makefile │ ├── debug.c │ ├── debug.h │ ├── main.c │ ├── storage.c │ └── storage.h ├── polymorphic_printer.c ├── printBinary.c ├── reading_sentences │ ├── main.c │ ├── readSentence.c │ └── readSentence.h ├── recursion+tree │ ├── Readme │ ├── arrayStack.c │ ├── arrayStack.h │ ├── asmEspExample.c │ ├── f1f2.c │ ├── factorial.c │ ├── factorial.s │ ├── largeTreeMain.c │ ├── mathTreeMain.c │ ├── opt.c │ ├── opt.s │ ├── stack.c │ ├── stack.h │ ├── sumExample.c │ ├── sumExample.s │ └── sumExample1.c ├── regexp │ ├── inp.txt │ ├── match.py │ └── regex_groups.c ├── remove_digits.c ├── return_local_address_mistake.cpp ├── sort_and_search.c ├── stack_exeptions.cpp ├── structs │ ├── ex1.c │ ├── ex2.c │ ├── ex3.c │ ├── ex4.c │ └── point.h ├── textReading.c └── word_counter.c ├── libpng ├── Makefile ├── README.md ├── main.c ├── res.png └── test.png ├── videos ├── read_text.c └── substrings.c └── vulnerabilities ├── README.md ├── return_address_modification.c └── stack_variables_modification.c /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Object files 5 | *.o 6 | *.ko 7 | *.obj 8 | *.elf 9 | 10 | # Linker output 11 | *.ilk 12 | *.map 13 | *.exp 14 | 15 | # Precompiled Headers 16 | *.gch 17 | *.pch 18 | 19 | # Libraries 20 | *.lib 21 | *.a 22 | *.la 23 | *.lo 24 | 25 | # Shared objects (inc. Windows DLLs) 26 | *.dll 27 | *.so 28 | *.so.* 29 | *.dylib 30 | 31 | # Executables 32 | *.exe 33 | *.out 34 | *.app 35 | *.i*86 36 | *.x86_64 37 | *.hex 38 | 39 | # Debug files 40 | *.dSYM/ 41 | *.su 42 | *.idb 43 | *.pdb 44 | 45 | # Kernel Module Compile Results 46 | *.mod* 47 | *.cmd 48 | .tmp_versions/ 49 | modules.order 50 | Module.symvers 51 | Mkfile.old 52 | dkms.conf 53 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # pr1-examples 2 | 3 | ## lectures 4 | Примеры кода, приводимые на лекциях 5 | 6 | ## vulnerabilities 7 | Примеры эксплуатации уязвимостей, порожденных ошибками программистов 8 | 9 | ## interestingness 10 | Интересности и не попавшие в другие разделы примеры 11 | 12 | -------------------------------------------------------------------------------- /hello.sh: -------------------------------------------------------------------------------- 1 | echo "hello world" 2 | -------------------------------------------------------------------------------- /interestingness/README.md: -------------------------------------------------------------------------------- 1 | # Интересности и не попавшие в другие разделы примеры 2 | ## colors.c 3 | Пример задания цвета текста, фона, стиля текста (подчеркнутый, зачеркнутый, полужирный) 4 | ## float_error.c 5 | Демо ошибки при операциях с вещественными числами (0.4≠0.4) 6 | ## hack_const.c 7 | Обход спецификатора `const` у указателя - аргумента функции. 8 | ## mem.c 9 | Пример иногда работающей программой с забытым `'\0'` в конце строки 10 | ## sum.c 11 | Пример иногда работающей суммы массива (`при N=4` уже не работающей) 12 | ## wow_i++.c 13 | Пример неопределенных выражений, результат которых зависит от компилятора и положения планет 14 | ## astyle_example/ 15 | Пример "плохого" и "хорошего" форматирования кода. "Хороший" получен из "плохого" утилитой [astyle](http://astyle.sourceforge.net/): 16 | ``` 17 | astyle --style=linux < bad_code.c > good_code.c 18 | ``` 19 | -------------------------------------------------------------------------------- /interestingness/astyle_example/bad_code.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | {int i,j,k; 5 | for(i=0;i<4;i++) 6 | {if(i>2) 7 | {for(j=0;j<5;j++) 8 | {printf("A");}} 9 | else 10 | {for(j=10;j<50;j++) 11 | {if(i%2) 12 | {printf("a"); 13 | }else 14 | {for(k=10;k>0;k--) 15 | {if(k>j) 16 | {printf("aaa");}}}printf("AA");}}printf("??");}} 17 | -------------------------------------------------------------------------------- /interestingness/astyle_example/good_code.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int i,j,k; 6 | for(i=0; i<4; i++) { 7 | if(i>2) { 8 | for(j=0; j<5; j++) { 9 | printf("A"); 10 | } 11 | } else { 12 | for(j=10; j<50; j++) { 13 | if(i%2) { 14 | printf("a"); 15 | } else { 16 | for(k=10; k>0; k--) { 17 | if(k>j) { 18 | printf("aaa"); 19 | } 20 | } 21 | } 22 | printf("AA"); 23 | } 24 | } 25 | printf("??"); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /interestingness/colors.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | 6 | // сначала цвет текста, потом фона 7 | printf("\033[9;31;40mКрасный; зачеркнутый; черный фон\033[0m"); 8 | printf("\n"); 9 | printf("\033[1;37;42mБелый; полужирный; зеленый фон\033[0m"); 10 | printf("\n"); 11 | printf("\033[4;34;43mСиний; подчеркнутый; желтый фон\033[0m"); 12 | printf("\n"); 13 | printf("\033[9;32;47mЗеленый; зачеркнутый; белый фон\033[0m"); 14 | printf("\n"); 15 | printf("\033[4;33;44mЖелтый; подчеркнутый; синий фон\033[0m"); 16 | printf("\n"); 17 | printf("\033[1;30;41mЧерный; полужирный; красный фон\033[0m"); 18 | printf("\n"); 19 | return 0; 20 | 21 | 22 | } 23 | -------------------------------------------------------------------------------- /interestingness/epsilon/Readme.md: -------------------------------------------------------------------------------- 1 | # Epsilon example 2 | 3 | Казалось бы, невнимательность при использовании операций с числами с плавающей точкой не может привести к масштабным последствиям. 4 | Максимум, не правильно обработаются "граничные" значения. Но это суждение в корне неверно. 5 | 6 | Чуть более сложные математические операции могут быть крайне чувствительны к ненулевым значениям. 7 | 8 | Так, например, кватернион заданный `-0.999978, 0.0, 0.0, -0.00666627` при преобразовании в Эйлерову форму даст тройку углов `-0,0; -0.0; 0.0133326`. 9 | То есть меньше градуса (`0.763904`) вокруг оси Z 10 | 11 | Если входные значения изменятся незначительным образом `-0.999978, 7.68307e-08, 7.68307e-08, -0.00666627`, в Эйлеровой форме это уже будет `3.14159; -3.14159; -3.12826`. 12 | Преобразовав в градусы угол вращения вокруг оси Z получим `-179.236` градусов. Что очень существенно отличается от `0.763904` 13 | -------------------------------------------------------------------------------- /interestingness/epsilon/epsilon_example.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(){ 5 | Eigen::Quaterniond q(-0.999978, 0.0, 0.0, -0.00666627); 6 | auto euler = q.toRotationMatrix().eulerAngles(0, 1, 2); 7 | std::cout << "Euler from quaternion in roll, pitch, yaw"<< std::endl << euler << std::endl; 8 | std::cout<< euler[2] * 180 / M_PI< 2 | 3 | int main(){ 4 | 5 | float f = 1.0; 6 | f = f/5; 7 | float a = 0; 8 | a=f*2; 9 | 10 | printf("a = %f\n", a); 11 | printf("a == 0.4: %d\n", a ==0.4); 12 | printf("a - 0.4: %f\n", a-0.4); 13 | 14 | 15 | printf("a = %.20f\n", a); 16 | return 0; 17 | 18 | 19 | } 20 | -------------------------------------------------------------------------------- /interestingness/hack_const.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void fun(const float *c){ 4 | //*c = 777; //compilation error: assignment of read-only location ‘*c’ 5 | unsigned long long ull = (unsigned long long) c; 6 | float *f = (float *) ull; 7 | *f = 777; 8 | } 9 | 10 | 11 | int main() { 12 | 13 | float f = 10; 14 | printf("%f\n",f); 15 | fun(&f); 16 | printf("%f\n",f); 17 | 18 | return 0; 19 | 20 | 21 | } 22 | -------------------------------------------------------------------------------- /interestingness/mem.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define N 100 6 | 7 | int main() 8 | { 9 | 10 | char s[N]; 11 | int i; 12 | 13 | char *subs = malloc(N * sizeof(char)); 14 | //memset(subs, 'A', N-1); 15 | 16 | fgets(s, N, stdin); 17 | 18 | for(i=0;s[i]!='\n' && s[i]!='!';i++) 19 | subs[i] = s[i]; 20 | //subs[i]='\0'; 21 | printf("[%s]\n", subs); 22 | 23 | free(subs); 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /interestingness/preprocessor.c: -------------------------------------------------------------------------------- 1 | // Use gcc -E to see more 2 | #include 3 | #define N 10 4 | #define M N + N 5 | #define ABS(x) -x 6 | #define HELLO "Hola amigos" 7 | #define LETSGO main() 8 | #define BACKBACKBACK return 9 | 10 | int LETSGO{ 11 | 12 | printf(HELLO": %d\n", -N + ABS(M - N)); 13 | 14 | BACKBACKBACK 0; 15 | } 16 | -------------------------------------------------------------------------------- /interestingness/sum.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define N 5 4 | 5 | int main() 6 | { 7 | int n = 4; 8 | int a[N]={10, 20, 30, 40}; 9 | int i=0; 10 | int sum=0; 11 | 12 | for(;i<=n;i++){ 13 | printf("a[%d]=%d; ", i, a[i]); 14 | sum+=a[i]; 15 | } 16 | printf("\n sum=%d\n", sum); 17 | return 0; 18 | } 19 | -------------------------------------------------------------------------------- /interestingness/wow_i++.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main(){ 4 | int i = 0; 5 | i = ++i + i++; 6 | printf("i = %d\n",i); 7 | 8 | i=0; 9 | i = 1 + i++; 10 | printf("i = %d\n",i); 11 | 12 | i=0; 13 | i = ++i + 1 + ++i; 14 | printf("i = %d\n",i); 15 | } 16 | 17 | /* 18 | gcc: 19 | i = 3 20 | i = 1 21 | i = 4 22 | */ 23 | /* 24 | clang: 25 | i = 2 26 | i = 1 27 | i = 4 28 | */ 29 | /* 30 | vc: 31 | i = 3 32 | i = 2 33 | i = 5 34 | */ 35 | 36 | -------------------------------------------------------------------------------- /lectures/08-11-18-lecture/2dim_array.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void f(int **buf){ 5 | *buf = malloc(sizeof(int)*10); 6 | (*buf)[0] = 1234; 7 | } 8 | 9 | int main(){ 10 | 11 | int **arr; 12 | arr = malloc(3 * sizeof(int*)); 13 | for(int i=0; i<3; i++) 14 | arr[i] = malloc(sizeof(int)*3); 15 | 16 | for(int i=0; i<3; i++) 17 | for(int j=0; j<3; j++) 18 | arr[i][j] = i*10+j; 19 | 20 | for(int i=0; i<3; i++){ 21 | for(int j=0; j<3; j++) 22 | printf("%d ", (arr[i])[j]); 23 | printf("\n"); 24 | } 25 | // free(arr); 26 | for(int i=0; i<3; i++) 27 | free(arr[i]); 28 | 29 | free(arr); 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /lectures/08-11-18-lecture/enum.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | enum En{ 5 | OK, 6 | WRONG_ADDRESS, 7 | MALLOC_ERR 8 | }; 9 | 10 | enum En create_array(int **a, int n); 11 | 12 | int main(){ 13 | enum En u = 1111; 14 | printf("%d\n", u); 15 | int *a; 16 | int n = -10; 17 | u = create_array(&a, n); 18 | switch(u){ 19 | case OK: 20 | printf("OK\n"); 21 | break; 22 | case WRONG_ADDRESS: 23 | printf("WA\n"); 24 | return 0; 25 | case MALLOC_ERR: 26 | printf("MERR\n"); 27 | return 0; 28 | } 29 | 30 | for(int i=0; i 2 | 3 | 4 | struct Point{ 5 | int x; 6 | char s[30]; 7 | char *s; 8 | int y; 9 | }; 10 | 11 | void printPoint(const struct Point *p){ 12 | printf("(%d;%d)\n", (*p).x, p->y); 13 | } 14 | 15 | struct Point createPoint(int x, int y){ 16 | struct Point p1 = {x, y}; 17 | return p1; 18 | } 19 | 20 | 21 | 22 | int main(){ 23 | struct Point p = createPoint(123,77); 24 | printPoint(&p); 25 | // p.x = 10; 26 | // p.y = 11; 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /lectures/08-11-18-lecture/union.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | union U{ 4 | struct S1 s; 5 | char b; 6 | }; 7 | 8 | int main(){ 9 | union U u; 10 | u.a = 0; 11 | u.b = 120; 12 | printf("%d\n", u.a); 13 | 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /lectures/17oct22_read_unlim_str/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define N 10 5 | 6 | int* initIntArray(int n){ 7 | // int *arr = (int*)malloc(sizeof(int)*n); 8 | int *arr = calloc(n, sizeof(int)); 9 | for(int i=0; i %d\n", cap, cap+5); 24 | char *t = realloc(s, cap+5); 25 | if(t){ 26 | s = t; 27 | cap += 5; 28 | }else { 29 | // error handler 30 | } 31 | } 32 | s[i] = c; 33 | i++; 34 | } 35 | s[i] = '\0'; 36 | puts(s); 37 | 38 | 39 | int *p = initIntArray(30); 40 | int *temp = realloc(p, sizeof(int)*60); 41 | if(temp){ // temp != NULL 42 | p = temp; 43 | } else { 44 | // ??? 45 | } 46 | 47 | free(p); 48 | 49 | 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /lectures/19-04-21-lec/README.md: -------------------------------------------------------------------------------- 1 | ## Полезности 2 | 3 | BST на рекурсии: https://habr.com/ru/post/267855/ 4 | Обходы: https://www.math.spbu.ru/user/nlebedin/2-year/traverse.pdf 5 | Обходы: https://habr.com/ru/post/144850/ 6 | 7 | -------------------------------------------------------------------------------- /lectures/README.md: -------------------------------------------------------------------------------- 1 | ## dir_files 2 | Просмотр всех вложенных директорий и печать на экран файлов, имя которых соответствует шаблону 3 | 4 | ## doxygen 5 | Система документирования исходных кодов. Пример с документированием stack.h 6 | 7 | ## find_regex 8 | Поиск файлов с использованием утилиты `find` и регулярного выражения 9 | 10 | ## function_pointers 11 | Указатели на функции; полиморфный принтер; универсальный поиск 12 | 13 | ## getopt 14 | Использование функций `getopt` и `getopt_long` для работы с ключами программы при разработке CLI 15 | 16 | ## num_storage 17 | Makefile. Продолжение диалоговой программы для хранения чисел (numStorage.c) но уже в нескольких файлах 18 | 19 | ## printBinary 20 | Печать числа в бинарном виде 21 | 22 | ## remove_digits 23 | Пример удаления цифр из строки 24 | 25 | ## reading_sentences 26 | Ввод предложений произвольной длины 27 | 28 | ## regexp 29 | Использование регулярных выражений в программе на С (стандартная библиотека языка).
30 | 31 | Где поучиться: https://regexone.com/
32 | Полигон для испытаний: https://regex101.com/ 33 | 34 | _Утилиты, которые Вы используете каждый день (`grep` и `find`) тоже умеют работать с регулярными выражениями._ 35 | 36 | ## exeptions.cpp 37 | Простой пример использования механизма исключений 38 | 39 | ## hashtable.c 40 | Простая хэш-таблица 41 | 42 | ## return_local_address_mistake.cpp 43 | Демонстрация ошибки: возвращение функцией адреса локальной переменной 44 | 45 | ## list_based_stack.c 46 | Стек на основе списка. Обратите внимание, что интерфейс стека скрывает его реализацию, а реализация не зависит от типа хранящихся в стеке данных 47 | 48 | ## mim_ssprintscan.c 49 | Wat-пример определения функции main внутри функции main, sscanf, sprintf 50 | 51 | ## numStorage.c 52 | Диалоговая программа для хранения чисел 53 | 54 | ## stack_exeptions.cpp 55 | Пользовательский класс `Stack` и собственные исключения 56 | 57 | ## word_counter.c 58 | Счетчик слов в файле 59 | -------------------------------------------------------------------------------- /lectures/arrayStack.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | typedef int type; 4 | #define ST_SIZE 20 5 | 6 | typedef struct ArrayStack{ 7 | type arr[ST_SIZE]; 8 | int sp; 9 | } ArrayStack; 10 | 11 | ArrayStack createStack(){ 12 | ArrayStack stack = {{0},-1}; 13 | return stack; 14 | } 15 | 16 | void push(ArrayStack *stack, type val){ 17 | stack->arr[++(stack->sp)] = val; 18 | } 19 | 20 | type pop(ArrayStack *stack){ 21 | return stack->arr[(stack->sp)--]; 22 | } 23 | 24 | type top(ArrayStack *stack){ 25 | return stack->arr[(stack->sp)]; 26 | } 27 | 28 | int isEmpty(ArrayStack *stack){ 29 | return stack->sp == -1; 30 | } 31 | 32 | int main(){ 33 | ArrayStack stack = createStack(); 34 | printf("%d\n", isEmpty(&stack)); 35 | for(int i=0; i<10;i++) 36 | push(&stack, i); 37 | while(!isEmpty(&stack)){ 38 | printf("%d\n", pop(&stack)); 39 | } 40 | 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /lectures/bmp/bmp.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #pragma pack (push, 1) 5 | typedef struct 6 | { 7 | unsigned short signature; 8 | unsigned int filesize; 9 | unsigned short reserved1; 10 | unsigned short reserved2; 11 | unsigned int pixelArrOffset; 12 | } BitmapFileHeader; 13 | 14 | typedef struct 15 | { 16 | unsigned int headerSize; 17 | unsigned int width; 18 | unsigned int height; 19 | unsigned short planes; 20 | unsigned short bitsPerPixel; 21 | unsigned int compression; 22 | unsigned int imageSize; 23 | unsigned int xPixelsPerMeter; 24 | unsigned int yPixelsPerMeter; 25 | unsigned int colorsInColorTable; 26 | unsigned int importantColorCount; 27 | } BitmapInfoHeader; 28 | 29 | typedef struct 30 | { 31 | unsigned char b; 32 | unsigned char g; 33 | unsigned char r; 34 | } Rgb; 35 | 36 | #pragma pack(pop) 37 | 38 | void printFileHeader(BitmapFileHeader header){ 39 | printf("signature:\t%x (%hu)\n", header.signature, header.signature); 40 | printf("filesize:\t%x (%u)\n", header.filesize, header.filesize); 41 | printf("reserved1:\t%x (%hu)\n", header.reserved1, header.reserved1); 42 | printf("reserved2:\t%x (%hu)\n", header.reserved2, header.reserved2); 43 | printf("pixelArrOffset:\t%x (%u)\n", header.pixelArrOffset, header.pixelArrOffset); 44 | } 45 | 46 | void printInfoHeader(BitmapInfoHeader header){ 47 | printf("headerSize:\t%x (%u)\n", header.headerSize, header.headerSize); 48 | printf("width: \t%x (%u)\n", header.width, header.width); 49 | printf("height: \t%x (%u)\n", header.height, header.height); 50 | printf("planes: \t%x (%hu)\n", header.planes, header.planes); 51 | printf("bitsPerPixel:\t%x (%hu)\n", header.bitsPerPixel, header.bitsPerPixel); 52 | printf("compression:\t%x (%u)\n", header.compression, header.compression); 53 | printf("imageSize:\t%x (%u)\n", header.imageSize, header.imageSize); 54 | printf("xPixelsPerMeter:\t%x (%u)\n", header.xPixelsPerMeter, header.xPixelsPerMeter); 55 | printf("yPixelsPerMeter:\t%x (%u)\n", header.yPixelsPerMeter, header.yPixelsPerMeter); 56 | printf("colorsInColorTable:\t%x (%u)\n", header.colorsInColorTable, header.colorsInColorTable); 57 | printf("importantColorCount:\t%x (%u)\n", header.importantColorCount, header.importantColorCount); 58 | } 59 | 60 | void swap(char *a, char *b){ 61 | char t = *a; 62 | *a = *b; 63 | *b = t; 64 | } 65 | 66 | unsigned int padding(unsigned int w){ 67 | return (4 - (w * sizeof(Rgb)) % 4) % 4; 68 | } 69 | 70 | unsigned int row_len(unsigned int w){ 71 | return w * sizeof(Rgb) + padding(w); 72 | } 73 | 74 | int main(){ 75 | FILE *f = fopen("simpsonsvr.bmp", "rb"); 76 | BitmapFileHeader bmfh; 77 | BitmapInfoHeader bmif; 78 | fread(&bmfh,1,sizeof(BitmapFileHeader),f); 79 | fread(&bmif,1,sizeof(BitmapInfoHeader),f); 80 | printFileHeader(bmfh); 81 | printInfoHeader(bmif); 82 | 83 | unsigned int H = bmif.height; 84 | unsigned int W = bmif.width; 85 | 86 | Rgb **arr = malloc(H*sizeof(Rgb*)); 87 | for(int i=0; i 2 | 3 | struct S{ 4 | int a; 5 | std::string s; 6 | }; 7 | 8 | int cmp(const void *a, const void *b){ 9 | S *aa = (S*) a; 10 | S *bb = (S*) b; 11 | return aa->s.compare(bb->s); 12 | } 13 | 14 | int main(){ 15 | struct S arr[] = {{10, "qwer"}, {23, "asdadf"}, {5553, "dsdfsa"}}; 16 | const int n = sizeof(arr)/sizeof(S); 17 | for(int i=0; i 2 | 3 | struct S{ 4 | int a; 5 | std::string *s; 6 | }; 7 | 8 | int cmp(const void *a, const void *b){ 9 | S *aa = (S*) a; 10 | S *bb = (S*) b; 11 | return aa->s->compare(*(bb->s)); 12 | } 13 | 14 | int main(){ 15 | struct S arr[] = {{10, new std::string("qwer")}, {23, new std::string("asdadf")}, {5553, new std::string("dsdfsa")}}; 16 | const int n = sizeof(arr)/sizeof(S); 17 | for(int i=0; i 2 | #include 3 | #include 4 | 5 | struct S{ 6 | int a; 7 | std::string s; 8 | }; 9 | 10 | bool cmp(S a, S b){ 11 | return a.s v = {{10, "qwer"}, {23, "asdadf"}, {5553, "dsdfsa"}}; 16 | for(S &elem: v) 17 | std::cout< 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #define INIT 10 8 | 9 | struct Text{ 10 | wchar_t **buf; 11 | int size; 12 | int n; 13 | }; 14 | 15 | wchar_t* readSentence(){ 16 | int size = INIT; 17 | int n = 0; 18 | wchar_t* buf = malloc(size * sizeof(wchar_t)); 19 | wchar_t wc; 20 | do{ 21 | wc = fgetwc(stdin); 22 | buf[n] = wc; 23 | n++; 24 | if(n == size - 2){ 25 | size+=INIT; 26 | buf = realloc(buf, size * sizeof(wchar_t)); 27 | } 28 | }while(!wcschr(L"!?.\n", wc)); 29 | buf[n] = L'\0'; 30 | return buf; 31 | } 32 | 33 | struct Text readText(){ 34 | int size = INIT; 35 | int n = 0; 36 | int nc = 0; 37 | wchar_t** buf = malloc(size * sizeof(wchar_t*)); 38 | while(1){ 39 | wchar_t *ws = readSentence(); 40 | if(ws[0]==L'\n'){ 41 | nc++; 42 | free(ws); 43 | } 44 | else{ 45 | nc = 0; 46 | buf[n] = ws; 47 | n++; 48 | if(n == size - 2){ 49 | size+=INIT; 50 | buf = realloc(buf, size * sizeof(wchar_t*)); 51 | } 52 | } 53 | if(nc == 2) 54 | break; 55 | } 56 | struct Text text; // text ={buf,size,n} 57 | text.buf = buf; 58 | text.size = size; 59 | text.n = n; 60 | return text; 61 | 62 | } 63 | 64 | 65 | int cmp (const void * a, const void * b) 66 | { 67 | wchar_t* aa = *((wchar_t**)a); 68 | wchar_t* bb = *((wchar_t**)b); 69 | return wcscmp(aa, bb); 70 | } 71 | 72 | int main() 73 | { 74 | setlocale(LC_ALL,""); 75 | /* struct Text text = readText(); 76 | for(int i=0; i 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | int isValid(char *filename){ 8 | char *regexp = "^test-[[:digit:]]{4}\\.txt$"; 9 | regex_t regexComp; 10 | 11 | if(regcomp(®exComp, regexp, REG_EXTENDED)){ 12 | return 0; 13 | } 14 | 15 | return regexec(®exComp, filename, 0, NULL, 0) == 0; 16 | } 17 | 18 | void printFile(char* filename, int pad){ 19 | FILE *f = fopen(filename, "r"); // "r", "w", "a" 20 | if(!f) 21 | return; 22 | for(int i=0;id_type == DT_DIR && strcmp(de->d_name, ".") != 0 && 44 | strcmp(de->d_name, "..") != 0){ 45 | int len = strlen(nextDir); 46 | strcat(nextDir, "/"); 47 | strcat(nextDir,de->d_name); 48 | listDir(nextDir, pad+1); 49 | nextDir[len] = '\0'; 50 | } 51 | if(de->d_type == DT_REG && isValid(de->d_name)){ 52 | int len = strlen(nextDir); 53 | strcat(nextDir, "/"); 54 | strcat(nextDir,de->d_name); 55 | printFile(nextDir, pad); 56 | nextDir[len] = '\0'; 57 | } 58 | de = readdir(dir); 59 | } 60 | closedir(dir); 61 | 62 | } 63 | 64 | int main(int argc, char **argv, char **env){ 65 | /*char **tmp = env; 66 | while(*tmp){ 67 | printf("%s", *tmp); 68 | tmp++; 69 | }*/ 70 | if(argc != 2){ 71 | printf("use ./prog \n"); 72 | return 0; 73 | } 74 | 75 | listDir(argv[1], 0); 76 | 77 | 78 | return 0; 79 | } 80 | -------------------------------------------------------------------------------- /lectures/dir_files/test-0001.txt: -------------------------------------------------------------------------------- 1 | this is test-0001 2 | 12312325 3 | @#$%^ 4 | -------------------------------------------------------------------------------- /lectures/dir_files/test-0002.txt: -------------------------------------------------------------------------------- 1 | this is test-0002 2 | WERTY 3 | zzxcvb 4 | -------------------------------------------------------------------------------- /lectures/doxygen/stack.h: -------------------------------------------------------------------------------- 1 | /** 2 | * @file stack.h 3 | * @brief Интерфейс стека 4 | * @author Константин Чайка 5 | * @version 1.0 6 | * @date февраль 2018 7 | * @warning файл написан с целью демонстрации и может содержать ошибки 8 | * @see https://en.wikipedia.org/wiki/Stack_(abstract_data_type) 9 | * 10 | * Интерфейс структуры данных "стек", примерно который ожидается от студентов первого курса 11 | * весеннего семестра при реализации второй рабораторной работы. 12 | *
Можно отметить, что интерфейс работы со стеком остается неизменным вне зависимости от реализации. 13 | */ 14 | 15 | 16 | /** 17 | * @brief Тип данных, хранящихся в стеке. 18 | * 19 | * Реализация стека не зависит от конкретного типа данных, 20 | * поэтому он может быть выбран в зависимости от решаемой задачи. 21 | */ 22 | typedef int type; 23 | 24 | /** 25 | * @brief Структура, хранящая в себе представление стека 26 | * 27 | * Такой подход скрывает от пользователя реальную структуру стека. 28 | * Текущая реализация выполнена на основе массива, однако это может быть легко изменено. 29 | * @note При реализации на основе списка крайне рекомендуется завести отдельную структуру 30 | * для узла списка, а в структуре Stack хранить указатель на голову списка. 31 | */ 32 | struct Stack{ 33 | type *array; /**< Массив для хранения элементов стека. */ 34 | size_t capacity; /**< Фактический размер массива Stack#array*/ 35 | size_t size; /**< Количество элементов хранящихся в массива (размер стека) */ 36 | }; 37 | 38 | /** 39 | * @brief Инициализирует стек 40 | 41 | * Функция, которая инициализирует структуру типа Stack для того, 42 | * что бы его можно было в дальнейшем использовать. Она устанавливает начальные значения 43 | * полей структуры. Стек после его инициализации пуст.
44 | * Пример использования: 45 | * @code{.c} 46 | * struct Stack stack = initStack(); 47 | * push(stack, 10); 48 | * @endcode 49 | * Следует учитывать, что использование стека без его инициализации 50 | * может привести к неопределенному поведению. 51 | * @return Структура, представляющая собой инициализированный пустой стек. 52 | */ 53 | struct Stack initStack(); 54 | 55 | /** 56 | * @brief Помещает элемент в стек 57 | * 58 | * Помещает элемент на вершину стека и сообщает удалось ли это сделать. 59 | * @param stack Структура, хранящая в себе представление стека. 60 | * @param elem Элемент, который надо поместить в стек, заданный @p stack. 61 | * @return 0 - если вставка прошла @b успешно и значение отличное от нуля в противном случае. 62 | * @note Вставка может завершиться ошибкой, если, например, не удалось выделить память. 63 | */ 64 | int push(struct Stack stack, type elem); 65 | 66 | /** 67 | * @brief Извлекает элемент из стека 68 | * 69 | * Извлекает элемент из стека, возвращая его. 70 | * @param stack Структура, хранящая в себе представление стека. 71 | * @return Элемент на вершине стека. 72 | * @warning Функция не проверяет пуст ли стек и поэтому вызов pop при пустом стеке 73 | * может привести к аварийному завершению программы. 74 | */ 75 | type pop(struct Stack stack); 76 | 77 | /** 78 | * @brief Возвращает элемент на вершине стека 79 | * 80 | * Возвращает элемент на вершине стека не извлекая его. 81 | * @param stack Структура, хранящая в себе представление стека. 82 | * @return Элемент на вершине стека. 83 | * @warning Функция не проверяет пуст ли стек и поэтому вызов pop при пустом стеке 84 | * может привести к аварийному завершению программы. 85 | */ 86 | type top(struct Stack stack); 87 | 88 | /** 89 | * @brief Проверка на пустоту 90 | * 91 | * Проверяет, является ли стек пустым. 92 | * @param stack Структура, хранящая в себе представление стека. 93 | * @return @b 1, если стек пуст и @b 0 в противном случае. 94 | */ 95 | int isEmpty(struct Stack stack); 96 | 97 | /** 98 | * @brief Возвращает размер стека 99 | * 100 | * Возвращает количество элементов фактически хранящихся в стеке. 101 | * @param stack Структура, хранящая в себе представление стека. 102 | * @return количество элементов в стеке. 103 | */ 104 | int count(struct Stack stack); 105 | -------------------------------------------------------------------------------- /lectures/exeptions.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | //#include 3 | 4 | int f(int n) { 5 | if(n > 1) 6 | throw 777; 7 | if(n<0) 8 | throw 45; 9 | return 0; 10 | } 11 | 12 | int main(){ 13 | try{ 14 | try{ 15 | std::cout<<"["; 16 | f(-10); 17 | std::cout<<"]"; 18 | } catch(int e){ 19 | std::cout<<"catched: "< 0; i-=1 )) 4 | do 5 | let "num = 10000+$RANDOM" 6 | let "num1 = 100+$RANDOM" 7 | let "num2 = 100+$RANDOM" 8 | touch "test.log.$num.zip" 9 | touch "test.log.$num-$num1.zip" 10 | touch "test.log.$num-$num1-$num2.zip" 11 | 12 | let "num = 1000+$RANDOM%9990" 13 | let "num1 = 10+$RANDOM%90" 14 | let "num2 = 10+$RANDOM%90" 15 | touch "test.log.$num1.zip" 16 | touch "test.log.$num-$num1.zip" 17 | touch "test.log.$num-$num1-$num2.zip" 18 | 19 | done 20 | 21 | 22 | -------------------------------------------------------------------------------- /lectures/function_pointers/example1.c: -------------------------------------------------------------------------------- 1 | // Programming 1. Sample at 2017-03-02-13-55.55 2 | #include 3 | 4 | struct Person 5 | { 6 | const char *name; 7 | int age; 8 | } person; 9 | 10 | void print_nice(const struct Person *p) 11 | { 12 | printf("Person %s age %d\n",p->name,p->age); 13 | } 14 | 15 | void print_ugly(const struct Person *p) 16 | { 17 | printf("[%s,%d]\n",p->name,p->age); 18 | } 19 | 20 | void print(const struct Person *obj, 21 | void (*printer)(const struct Person*)) 22 | { 23 | printer(obj); 24 | } 25 | 26 | int main(/*int c, char **v */) 27 | { 28 | person.name = "Vasya"; 29 | person.age = 15; 30 | 31 | print(&person,print_nice); 32 | print(&person,print_ugly); 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /lectures/function_pointers/example2.c: -------------------------------------------------------------------------------- 1 | // Programming 1. Sample at 2017-03-02-13-55.55 2 | #include 3 | 4 | struct Person 5 | { 6 | const char *name; 7 | int age; 8 | void (*print)(const struct Person*); 9 | void (*printer)(const struct Person*); 10 | } person1, person2; 11 | 12 | void print_nice(const struct Person *p) 13 | { 14 | printf("Person %s age %d\n",p->name,p->age); 15 | } 16 | 17 | void print_ugly(const struct Person *p) 18 | { 19 | printf("[%s,%d]\n",p->name,p->age); 20 | } 21 | 22 | void print(const struct Person *obj) 23 | { 24 | obj->printer(obj); 25 | } 26 | 27 | 28 | 29 | int main(/*int c, char **v */) 30 | { 31 | person1.name = "Vasya"; 32 | person1.age = 15; 33 | person1.print = print; 34 | person1.printer = print_nice; 35 | 36 | person2.name = "Petya"; 37 | person2.age = 51; 38 | person2.print = print; 39 | person2.printer = print_ugly; 40 | 41 | person1.print(&person1); 42 | person2.print(&person2); 43 | 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /lectures/function_pointers/example3.c: -------------------------------------------------------------------------------- 1 | // Programming 1. Sample at 2018-02-15-14-55.05 2 | #include 3 | 4 | struct S{ 5 | int a; 6 | int b; 7 | }; 8 | 9 | void* search( void *key, 10 | void *arr, 11 | int n, 12 | int size, 13 | int (*comp)(const void *, const void *) 14 | ){ 15 | 16 | for(int i=0;ia == bb->a && aa->b == bb->b){ 30 | return 0; 31 | } 32 | if((aa->a + aa->b) - (bb->a + bb->b) > 0){ 33 | return 1; 34 | } 35 | return -1; 36 | } 37 | 38 | int main(){ 39 | struct S arr[]={{1,2},{3,4},{5,6},{6,7}}; 40 | struct S* value; 41 | struct S key={5,6}; 42 | 43 | value = search(&key, arr, 4, sizeof(struct S), comp); 44 | if(value){ 45 | printf("%zu\n", value - arr); 46 | }else{ 47 | printf("nooooo\n"); 48 | } 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /lectures/getopt/getopt.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | void printHelp(){ 6 | printf("getopt example\n"); 7 | printf("-f - final value\n"); 8 | printf("-r - reverse\n"); 9 | printf("-v - verbose\n"); 10 | printf("-h -? - help\n"); 11 | } 12 | 13 | struct Configs{ 14 | int final; 15 | int reverse; // 0 - false 16 | int verbose; // 0 - false 17 | }; 18 | 19 | int main(int argc, char* argv[]){ 20 | struct Configs config = {0, 0, 0}; 21 | char *opts = "f:rvh?"; 22 | int opt; 23 | opt = getopt(argc, argv, opts); 24 | while(opt!=-1){ 25 | switch(opt){ 26 | case 'f': 27 | // printf("get f with value: %d\n", atoi(optarg)); 28 | config.final = atoi(optarg); 29 | break; 30 | case 'r': 31 | config.reverse = 1; 32 | //printf("get r\n"); 33 | break; 34 | case 'v': 35 | //printf("get v\n"); 36 | config.verbose = 1; 37 | break; 38 | case 'h': 39 | case '?': 40 | printHelp(); 41 | return 0; 42 | } 43 | opt = getopt(argc, argv, opts); 44 | } 45 | argc -= optind; 46 | argv += optind; 47 | printf("final = %d\n", config.final); 48 | printf("verbose = %d\n", config.verbose); 49 | printf("reverse = %d\n", config.reverse); 50 | for(int i=0; i>%s\n", argv[i]); 52 | return 0; 53 | } 54 | -------------------------------------------------------------------------------- /lectures/getopt/getopt_long.c: -------------------------------------------------------------------------------- 1 | #include 2 | //#include 3 | #include 4 | #include 5 | 6 | void printHelp(){ 7 | printf("getopt example\n"); 8 | printf("-f - final value\n"); 9 | printf("-r - reverse\n"); 10 | printf("-v --verbose - verbose\n"); 11 | printf("-h -? - help\n"); 12 | } 13 | 14 | struct Configs{ 15 | int final; 16 | int reverse; // 0 - false 17 | int verbose; // 0 - false 18 | }; 19 | 20 | int main(int argc, char* argv[]){ 21 | struct Configs config = {0, 0, 0}; 22 | char *opts = "f:rvh?"; 23 | struct option longOpts[]={ 24 | {"verbose", no_argument, NULL, 'v'}, 25 | {"longlong", no_argument, NULL, 0}, 26 | {"long", no_argument, NULL, 0}, 27 | { NULL, 0, NULL, 0} 28 | }; 29 | int opt; 30 | int longIndex; 31 | opt = getopt_long(argc, argv, opts, longOpts, &longIndex); 32 | while(opt!=-1){ 33 | switch(opt){ 34 | case 'f': 35 | // printf("get f with value: %d\n", atoi(optarg)); 36 | config.final = atoi(optarg); 37 | break; 38 | case 'r': 39 | config.reverse = 1; 40 | //printf("get r\n"); 41 | break; 42 | case 'v': 43 | //printf("get v\n"); 44 | config.verbose = 1; 45 | break; 46 | case 'h': 47 | case '?': 48 | printHelp(); 49 | return 0; 50 | case 0: 51 | printf("->%s\n",longOpts[longIndex].name); 52 | } 53 | opt = getopt_long(argc, argv, opts, longOpts, &longIndex); 54 | } 55 | argc -= optind; 56 | argv += optind; 57 | printf("final = %d\n", config.final); 58 | printf("verbose = %d\n", config.verbose); 59 | printf("reverse = %d\n", config.reverse); 60 | for(int i=0; i>%s\n", argv[i]); 62 | return 0; 63 | } 64 | -------------------------------------------------------------------------------- /lectures/hashtable.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #define K 101 5 | // 8 bit 6 | unsigned char hash(char *arr, int n){ 7 | unsigned char res = 0; 8 | for(int i=0; iarr[i] = NULL; 25 | } 26 | } 27 | 28 | void add(struct hashtable *table, int key, int val){ 29 | unsigned char h = hash((char*)&key, sizeof(key)); 30 | struct pair *p = malloc(sizeof(struct pair)); 31 | p->key = key; 32 | p->val = val; 33 | table->arr[h] = p; 34 | } 35 | 36 | int contains(struct hashtable *table, int key){ 37 | unsigned char h = hash((char*)&key, sizeof(key)); 38 | if(table->arr[h] == NULL){ 39 | return 0; 40 | }else{ 41 | return table->arr[h]->key == key; 42 | } 43 | } 44 | 45 | void rem(struct hashtable *table, int key){ 46 | unsigned char h = hash((char*)&key, sizeof(key)); 47 | free(table->arr[h]); 48 | table->arr[h] = NULL; 49 | } 50 | 51 | int get(struct hashtable *table, int key){ 52 | unsigned char h = hash((char*)&key, sizeof(key)); 53 | if(table->arr[h]) 54 | return table->arr[h]->val; 55 | return 0; 56 | } 57 | 58 | int main(){ 59 | char s[10]; 60 | struct hashtable table; 61 | init(&table); 62 | add(&table, 2, 4); 63 | add(&table, 3, 9); 64 | add(&table, 4, 16); 65 | add(&table, 5, 25); 66 | for(int i=0; i<10; i++){ 67 | printf("%d: %d\n", i, contains(&table, i)); 68 | if(contains(&table, i)){ 69 | printf("[%d]\n", get(&table, i)); 70 | } 71 | } 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /lectures/libc/Makefile: -------------------------------------------------------------------------------- 1 | CC=gcc 2 | LDFLAGS=-lm 3 | SOURCES=$(wildcard *.c) 4 | EXECUTABLES=$(SOURCES:.c=.) 5 | 6 | all: $(EXECUTABLES) 7 | 8 | $(EXECUTABLES): 9 | $(CC) $@c $(LDFLAGS) -o $@out 10 | 11 | clean: 12 | rm -f *.out 13 | -------------------------------------------------------------------------------- /lectures/libc/assert.c: -------------------------------------------------------------------------------- 1 | #include 2 | #define NDEBUG 3 | #include 4 | 5 | int main() 6 | { 7 | int a = 10, b = 0; 8 | assert(b); 9 | printf("a/b = %d\n", a/b); 10 | return 0; 11 | } 12 | -------------------------------------------------------------------------------- /lectures/libc/complex.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | 6 | double complex z1 = 1.0 + 3.0 * I; 7 | double complex z2 = 1.0 - 4.0 * I; 8 | 9 | printf("Z1 \t= %.2f + %.2fi\nZ2 \t= %.2f %+.2fi\n", creal(z1), cimag(z1), creal(z2), cimag(z2)); 10 | 11 | double complex sum = z1 + z2; 12 | printf("Z1 + Z2 = %.2f %+.2fi\n", creal(sum), cimag(sum)); 13 | 14 | double complex difference = z1 - z2; 15 | printf("Z1 - Z2 = %.2f %+.2fi\n", creal(difference), cimag(difference)); 16 | 17 | double complex product = z1 * z2; 18 | printf("Z1 x Z2 = %.2f %+.2fi\n", creal(product), cimag(product)); 19 | 20 | double complex quotient = z1 / z2; 21 | printf("Z1 / Z2 = %.2f %+.2fi\n", creal(quotient), cimag(quotient)); 22 | 23 | double complex conjugate = conj(z1); 24 | printf("Z1 \t= %.2f %+.2fi\n", creal(conjugate), cimag(conjugate)); 25 | 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /lectures/libc/errno.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main() 7 | { 8 | FILE *f = fopen("no_such_file.txt", "r"); 9 | if(!f) 10 | perror("Error: "); 11 | errno = 0; 12 | perror("No error: "); 13 | sqrt(-10); 14 | perror("Error: "); 15 | 16 | return 0; 17 | } 18 | -------------------------------------------------------------------------------- /lectures/libc/fenv.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #pragma STDC FENV_ACCESS ON 6 | 7 | int main() 8 | { 9 | double one = 1.0; 10 | double zero = 0.0; 11 | feclearexcept(FE_ALL_EXCEPT); 12 | printf("1.0/0.0 = %lf\n", one/zero); 13 | if(fetestexcept(FE_DIVBYZERO)) { 14 | printf("division by zero\n"); 15 | } else { 16 | printf("no divsion by zero\n"); 17 | } 18 | feclearexcept(FE_ALL_EXCEPT); 19 | printf("1.0/10 = %lf\n", one/10); 20 | if(fetestexcept(FE_INEXACT)) { 21 | printf("inexact result\n"); 22 | } else { 23 | printf("no inexact result\n"); 24 | } 25 | 26 | feclearexcept(FE_ALL_EXCEPT); 27 | printf("sqrt(-1) = %lf\n",sqrt(-1)); 28 | if(fetestexcept(FE_INVALID)) { 29 | printf("invalid result\n"); 30 | } else { 31 | printf("no invalid result\n"); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /lectures/libc/float.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #pragma STDC FENV_ACCESS ON 5 | int main() 6 | { 7 | printf("FLT_MAX = %f\n", FLT_MAX); 8 | printf("FLT_EPSILON = %.30f\n", FLT_EPSILON); 9 | printf("FLT_ROUNDS = %d\n", FLT_ROUNDS); 10 | fesetround(FE_TOWARDZERO); 11 | printf("FLT_ROUNDS = %d\n", FLT_ROUNDS); 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /lectures/libc/iso646.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(){ 5 | int a = 0; 6 | int b = 10; 7 | if(a and b) 8 | printf("and\n"); 9 | if(a or b) 10 | printf("or\n"); 11 | b = a bitand b; 12 | printf("%d\n",b); 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /lectures/libc/locale.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() 6 | { 7 | setlocale(LC_ALL, ""); 8 | 9 | struct lconv* currentlocale; 10 | struct tm * timeinfo; 11 | time_t rawtime; 12 | char buffer [80]; 13 | 14 | currentlocale = localeconv(); 15 | printf("currentlocale->decimal_point is '%c'\n", *(currentlocale->decimal_point)); 16 | 17 | time (&rawtime); 18 | timeinfo = localtime (&rawtime); 19 | 20 | strftime (buffer,80,"Now it's %c.",timeinfo); 21 | printf("%s\n",buffer); 22 | 23 | return 0; 24 | } 25 | -------------------------------------------------------------------------------- /lectures/libc/math.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define DEG_TO_RAD(x) x/180.0*M_PI 5 | 6 | int main() 7 | { 8 | 9 | printf("ceil(1.5) = %f\n", ceil(1.5)); 10 | printf("floor(1.5) = %f\n", floor(1.5)); 11 | printf("fmod(5.0, 2.0) = %f\n", fmod(5.0, 2.0)); 12 | printf("log10(1024) = %f\n", log10(1024)); 13 | printf("sin(PI) = %f\n", sin(M_PI_2)); 14 | printf("sin(PI) = %f\n", sin(DEG_TO_RAD(30))); 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /lectures/libc/setjmp.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | jmp_buf bufferA, bufferB; 5 | 6 | void routineB(); // forward declaration 7 | 8 | void routineA() 9 | { 10 | int r ; 11 | 12 | printf("(A1)\n"); 13 | 14 | r = setjmp(bufferA); 15 | if (r == 0) routineB(); 16 | 17 | printf("(A2) r=%d\n",r); 18 | 19 | r = setjmp(bufferA); 20 | if (r == 0) longjmp(bufferB, 20001); 21 | 22 | printf("(A3) r=%d\n",r); 23 | 24 | r = setjmp(bufferA); 25 | if (r == 0) longjmp(bufferB, 20002); 26 | 27 | printf("(A4) r=%d\n",r); 28 | } 29 | 30 | void routineB() 31 | { 32 | int r; 33 | 34 | printf("(B1)\n"); 35 | 36 | r = setjmp(bufferB); 37 | if (r == 0) longjmp(bufferA, 10001); 38 | 39 | printf("(B2) r=%d\n", r); 40 | 41 | r = setjmp(bufferB); 42 | if (r == 0) longjmp(bufferA, 10002); 43 | 44 | printf("(B3) r=%d\n", r); 45 | 46 | r = setjmp(bufferB); 47 | if (r == 0) longjmp(bufferA, 10003); 48 | } 49 | 50 | 51 | int main(int argc, char **argv) 52 | { 53 | routineA(); 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /lectures/libc/signal.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void ctrlc(int signal){ 5 | printf("Nope!\n"); 6 | } 7 | 8 | int main() 9 | { 10 | //signal(SIGINT,ctrlc); 11 | while(1){ 12 | raise(SIGINT); 13 | } 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /lectures/libc/stdarg.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | void var(char *format, ...) 6 | { 7 | va_list ap; 8 | va_start(ap, format); 9 | if(!strcmp(format, "%d")) 10 | { 11 | int x = va_arg (ap, int); 12 | printf ("You passed decimal object with value %d\n", x); 13 | } 14 | 15 | if(!strcmp(format, "%s")) 16 | { 17 | char *p = va_arg (ap, char *); 18 | printf ("You passed c-string \"%s\"\n", p); 19 | } 20 | 21 | if(!strcmp(format, "%2int")) 22 | { 23 | int a = va_arg (ap, int); 24 | int b = va_arg (ap, int); 25 | 26 | printf ("You passed 2int: %d, %d\n", a,b); 27 | } 28 | va_end (ap); 29 | } 30 | 31 | int main(void) 32 | { 33 | var("%d", 255); 34 | var("%s", "test string"); 35 | var("%2int", 100, 200); 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /lectures/libc/stdbool.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() 5 | { 6 | _Bool b = false; 7 | if(b){ 8 | printf("b\n"); 9 | } 10 | if(!b){ 11 | printf("!b\n"); 12 | } 13 | 14 | if(true && !false){ 15 | printf("_Bool is cool!\n"); 16 | } 17 | 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /lectures/libc/stddef.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | //-fpack-struct 4 | struct car 5 | { 6 | char brand[31]; 7 | char hp[30]; 8 | double price; 9 | double tmp; 10 | } t; 11 | 12 | int main() 13 | { 14 | 15 | //смещение относительно начала. 16 | printf("%lu\n", offsetof(struct car, brand)); 17 | printf("%lu\n", offsetof(struct car, hp)); 18 | printf("%lu\n", offsetof(struct car, price)); 19 | printf("%lu\n", offsetof(struct car, tmp)); 20 | 21 | printf("\n"); 22 | //размеры членов структуры 23 | // printf("%lu\n", sizeof (t.brand)); 24 | // printf("%lu\n", sizeof (t.hp)); 25 | // printf("%lu\n", sizeof (t.price)); 26 | // printf("%lu\n", sizeof (t.tmp)); 27 | 28 | // размер занимаемый структурой в памяти. 29 | printf("sizeof struct = %lu\n", sizeof(struct car)); 30 | 31 | } 32 | 33 | -------------------------------------------------------------------------------- /lectures/libc/stdint.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | int main() 5 | { 6 | int32_t a = 100; 7 | intmax_t max = INTMAX_MAX; 8 | printf("%"PRId32"\n", a); 9 | printf("%jd\n", max); 10 | return 0; 11 | } 12 | -------------------------------------------------------------------------------- /lectures/libc/stdlib.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | void fnExit1 (void) 6 | { 7 | puts ("Exit function 1."); 8 | } 9 | 10 | void fnExit2 (void) 11 | { 12 | puts ("Exit function 2."); 13 | } 14 | 15 | int main() 16 | { 17 | // atexit (fnExit1); 18 | // atexit (fnExit2); 19 | 20 | // while(1){} 21 | 22 | char ff[]="3.1415"; 23 | float f; 24 | f = atof(ff); 25 | //printf("f = %f\n", f); 26 | srand(time(NULL)); 27 | //printf("%d\n", rand()); 28 | //printf("%d\n", rand()); 29 | 30 | system("gnome-mahjongg &"); 31 | 32 | div_t d = div(107, 25); 33 | printf("[%d;%d]\n", d.quot, d.rem); 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /lectures/libc/string.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define PRINT_STR(X) printf(#X" = %s\n", X) 5 | 6 | int main() 7 | { 8 | 9 | /* 10 | void *memccpy(void *, const void *, int, size_t); 11 | void *memchr(const void *, int, size_t); 12 | int memcmp(const void *, const void *, size_t); 13 | void *memcpy(void *, const void *, size_t); 14 | void *memmove(void *, const void *, size_t); 15 | void *memset(void *, int, size_t); 16 | =========== 17 | char *strcat(char *, const char *); 18 | char *strchr(const char *, int); 19 | int strcmp(const char *, const char *); 20 | int strcoll(const char *, const char *); 21 | char *strcpy(char *, const char *); 22 | size_t strcspn(const char *, const char *); 23 | char *strdup(const char *); 24 | char *strerror(int); 25 | size_t strlen(const char *); 26 | char *strncat(char *, const char *, size_t); 27 | int strncmp(const char *, const char *, size_t); 28 | char *strncpy(char *, const char *, size_t); 29 | char *strpbrk(const char *, const char *); 30 | char *strrchr(const char *, int); 31 | size_t strspn(const char *, const char *); 32 | char *strstr(const char *, const char *); 33 | char *strtok(char *, const char *); 34 | char *strtok_r(char *, const char *, char **); 35 | size_t strxfrm(char *, const char *, size_t); 36 | */ 37 | 38 | // void *memccpy(void *s1, const void *s2, int c, size_t n); 39 | // Descr: The memccpy() function copies bytes from memory area s2 into s1, stopping after the first occurrence of byte c (converted to an unsigned char) is copied, or after n bytes are copied, whichever comes first. If copying takes place between objects that overlap, the behaviour is undefined. 40 | // Ret: The memccpy() function returns a pointer to the byte after the copy of c in s1, or a null pointer if c was not found in the first n bytes of s2. 41 | //char s1[30]={0}; 42 | //char s2[]="What a nice string for memccpy function!"; 43 | //char *res = memccpy(s1,s2,'s', 20); 44 | //printf("%zd\n", res-s1); // 13 45 | //PRINT_STR((char*)memccpy(s1,s2,'!', 20)); // (null) 46 | 47 | // void *memchr(const void *s, int c, size_t n); 48 | // Descr: The memchr() function locates the first occurrence of c (converted to an unsigned char) in the initial n bytes (each interpreted as unsigned char) of the object pointed to by s. 49 | // Ret: The memchr() function returns a pointer to the located byte, or a null pointer if the byte does not occur in the object. 50 | 51 | //char s[]="What a nice string for memchr function!"; 52 | //char *pch; 53 | //pch = (char*) memchr (s, 's', strlen(s)); 54 | //if (pch!=NULL) 55 | // printf ("'s' index %zd.\n", pch-s); 56 | //else 57 | // printf ("'s' not found.\n"); 58 | 59 | /* 60 | char str[] = "memmove can be very useful......"; 61 | memmove (str+20,str+15,11); 62 | printf("after memmove str = {%s}\n", str); 63 | 64 | char *p = memchr(str, 'v', 30); 65 | if(p){ 66 | printf("memchr result = {%s}\n", p); 67 | } 68 | 69 | memset(str, 65, 10); 70 | printf("after memset str = {%s}\n", str); 71 | 72 | printf("strerror(0) = %s\n", strerror(0)); 73 | 74 | printf("strspn(\"lets see how it works!\", \"etsl \") = %zd\n", strspn("lets see how it works!", "etsl ")); 75 | 76 | printf("strpbrk(\"Some text& with ? some # signs \", \"?#&\") = %s\n", strpbrk("Some text& with ? some # signs ", "?#&")); 77 | 78 | 79 | char info[]="Tom.Sawyer,12:Mark;Twain"; 80 | p = strtok(info,";:.,"); 81 | while(p){ 82 | printf(">{%s}\n", p); 83 | p = strtok(NULL,";:.,"); 84 | } 85 | 86 | printf("strsignal(9) = %s\n", strsignal(9)); 87 | 88 | */ 89 | return 0; 90 | } 91 | -------------------------------------------------------------------------------- /lectures/libc/tgmath.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() { 6 | 7 | double dx=0, dy=0; 8 | float fx = 0, fy = 0; 9 | long double complex clx = 1.0 - 0.0 * I; 10 | long double complex cly = -1.0 - 0.0 * I; 11 | 12 | dy = sin(dx); //dy = sin(dx) 13 | fy = sin(fx); //fy = sinf(fx) 14 | cly = sin(clx); //cly = csinl(clyx) 15 | return 0; 16 | } 17 | -------------------------------------------------------------------------------- /lectures/libc/time.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int main() 6 | { 7 | 8 | 9 | 10 | printf("%ju\n",clock()); 11 | //for(long long i=0;i<1000000000;i++)sqrt(10); 12 | printf("%ju\n", clock()/CLOCKS_PER_SEC); 13 | 14 | time_t rawtime; 15 | time (&rawtime); 16 | printf("%ju\n",rawtime); 17 | printf("%s", ctime(&rawtime)); 18 | 19 | struct tm * timeinfo; 20 | timeinfo = localtime (&rawtime); 21 | printf("%s", asctime(timeinfo)); 22 | timeinfo->tm_mon = 0; 23 | printf("%s", asctime(timeinfo)); 24 | 25 | rawtime = 0; 26 | printf("%s", ctime(&rawtime)); 27 | 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /lectures/libc/wchar.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | int main() 7 | { 8 | char s[100]; 9 | printf(">>%d\n",fwide (stdout,0)); 10 | printf(">>%d\n",fwide (stdout,0)); 11 | // fgets(s, 100, stdin); 12 | // printf("{%s}\n",s); 13 | // printf("strlen(s) = %zd\n",strlen(s)); 14 | // for(int i=0;i 3 | #include 4 | typedef int dataType; 5 | 6 | struct Person 7 | { 8 | dataType data; 9 | struct Person *next; 10 | }; 11 | 12 | struct Person *list=NULL; 13 | 14 | void print_list(struct Person *list); 15 | 16 | void del_item(struct Person **list, int n); 17 | 18 | void add_item(struct Person **list, struct Person *item, int tail); 19 | 20 | struct Person* createNode(dataType n){ 21 | struct Person *node = (struct Person*) malloc(sizeof(struct Person)); 22 | node->data = n; 23 | node->next = NULL; 24 | return node; 25 | } 26 | 27 | int main(/*int c, char **v */) 28 | { 29 | add_item(&list, createNode(10),0); 30 | add_item(&list, createNode(20),0); 31 | add_item(&list, createNode(30),0); 32 | print_list(list); 33 | 34 | return 0; 35 | } 36 | 37 | void print_list(struct Person *list) 38 | { 39 | while(list) 40 | { 41 | printf("%d\n",list->data); 42 | list = list->next; 43 | } 44 | } 45 | 46 | void del_item(struct Person **list, int n) 47 | { 48 | if(*list == NULL) 49 | return; 50 | 51 | if(n==0) 52 | { 53 | (*list) = (*list)->next; 54 | return; 55 | } 56 | 57 | struct Person *current = *list; 58 | while(current && (n--) > 1) 59 | { 60 | current=current->next; 61 | } 62 | 63 | if(current->next) 64 | 65 | current->next = current->next->next; 66 | 67 | } 68 | 69 | void add_item(struct Person **list, struct Person *item, int tail) 70 | { 71 | if(*list == NULL) // adding 1st item 72 | { 73 | (*list) = item; 74 | return; 75 | } 76 | 77 | if(tail == 0) 78 | { 79 | item->next = *list; 80 | (*list) = item; 81 | return; 82 | } 83 | 84 | struct Person *current = *list; 85 | 86 | while(current) 87 | { 88 | if(current->next == NULL) 89 | { 90 | current->next = item; 91 | return; 92 | } 93 | else 94 | { 95 | current = current->next; 96 | } 97 | } 98 | } 99 | 100 | -------------------------------------------------------------------------------- /lectures/list/list_lect.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef struct Node{ 5 | int data; 6 | struct Node *next; 7 | } Node; 8 | 9 | Node* createNode(int a, Node *next){ 10 | Node *tmp = calloc(1, sizeof(Node)); 11 | tmp->data = a; 12 | tmp->next = next; 13 | return tmp; 14 | } 15 | 16 | void printList(Node* head){ 17 | printf("[ "); 18 | while(head){ 19 | printf("%d ", head -> data); 20 | head = head->next; 21 | } 22 | printf("]\n"); 23 | } 24 | 25 | void pushFront(Node **head, int n){ 26 | Node *tmp = createNode(n, *head); 27 | *head = tmp; 28 | } 29 | 30 | void pushBack(Node **head, int n){ 31 | if(!*head){ 32 | pushFront(head, n); 33 | return; 34 | } 35 | while((*head)->next){ 36 | *head = (*head)->next; 37 | } 38 | (*head)->next = createNode(n, NULL); 39 | } 40 | 41 | void insert(Node **head, int elem, int i){ 42 | if(!*head || !i){ 43 | pushFront(head, elem); 44 | return; 45 | } 46 | Node *cur = *head; 47 | Node *prev = NULL; 48 | while(cur && i>0){ 49 | prev = cur; 50 | cur = cur->next; 51 | i--; 52 | } 53 | Node *tmp = createNode(elem, cur); 54 | prev->next = tmp; 55 | } 56 | 57 | int rem(Node **head, int val){ 58 | if(!*head) 59 | return 0; 60 | if((*head)->data == val){ 61 | Node *t = *head; 62 | *head = (*head)->next; 63 | free(t); 64 | return 0; 65 | } 66 | Node *cur = *head; 67 | Node *prev = NULL; 68 | while(cur && cur->data != val){ 69 | prev = cur; 70 | cur = cur->next; 71 | } 72 | if(!cur) 73 | return -1; 74 | prev->next = cur->next; 75 | free(cur); 76 | return 0; 77 | 78 | } 79 | 80 | int main() 81 | { 82 | // Node *head = createNode(1, createNode(2,NULL)); 83 | Node *head = NULL; 84 | pushBack(&head,10); 85 | pushBack(&head,20); 86 | pushFront(&head, 30); 87 | // printList(head); 88 | insert(&head, 100, 70); 89 | insert(&head, 90, 3); 90 | insert(&head, 0, 0); 91 | insert(&head, -10, 0); 92 | printList(head); 93 | rem(&head, -10); 94 | printList(head); 95 | rem(&head, -10); 96 | printList(head); 97 | rem(&head, -15); 98 | printList(head); 99 | rem(&head, 100); 100 | printList(head); 101 | rem(&head, 20); 102 | printList(head); 103 | 104 | return 0; 105 | } 106 | 107 | -------------------------------------------------------------------------------- /lectures/list/list_swap.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct Node{ 5 | int n; 6 | struct Node *next; 7 | }; 8 | 9 | typedef struct Node Node; 10 | 11 | Node* createNode(int n, Node *next){ 12 | Node *node = malloc(sizeof(Node)); 13 | node->n = n; 14 | node->next = next; 15 | return node; 16 | } 17 | 18 | void swap_p(Node **a, Node **b){ 19 | Node *tmp = *a; 20 | *a = *b; 21 | *b = tmp; 22 | } 23 | 24 | void swap_nodes(Node *a_pred, Node *b_pred){ 25 | if(a_pred == b_pred) 26 | return; 27 | Node *a = a_pred->next; 28 | Node *b = b_pred->next; 29 | if(b->next == a){ // if a > b in order 30 | swap_p(&a, &b); 31 | swap_p(&a_pred, &b_pred); 32 | } 33 | if(a->next == b){ 34 | a_pred->next = b; 35 | a->next = b->next; 36 | b->next = a; 37 | return; 38 | } 39 | swap_p(&(a->next), &(b->next)); 40 | swap_p(&(a_pred->next), &(b_pred->next)); 41 | } 42 | 43 | void swap_any_nodes(Node ** root, Node *a_pred, Node *b_pred){ 44 | 45 | } 46 | 47 | void printList(Node *root){ 48 | printf("["); 49 | while (root) { 50 | printf("%d", root->n); 51 | root = root->next; 52 | if(root) 53 | printf(", "); 54 | } 55 | printf("]\n"); 56 | } 57 | 58 | void max_to_top(Node* root){ 59 | Node* pred = root; 60 | Node *a = pred->next; 61 | if(a==NULL) 62 | return; 63 | Node *b = a->next; 64 | while(b){ 65 | if(a->n > b->n){ 66 | swap_nodes(pred, a); 67 | } 68 | pred = a; 69 | a = b; 70 | b = b->next; 71 | } 72 | } 73 | 74 | int main(){ 75 | Node * a = createNode(50, NULL); 76 | Node * b = createNode(400, a); 77 | Node * c = createNode(30, b); 78 | Node * d = createNode(20, c); 79 | Node * e = createNode(60, d); 80 | Node *root = createNode(0,e); 81 | printList(root); 82 | //swap_nodes(c,b); 83 | max_to_top(root); 84 | printList(root); 85 | return 0; 86 | } 87 | -------------------------------------------------------------------------------- /lectures/list/list_swap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using std::cout; 3 | using std::endl; 4 | struct Elem{ 5 | int data; 6 | Elem *next; 7 | }; 8 | 9 | struct List{ 10 | Elem *head; 11 | }; 12 | 13 | void printList(const List *list){ 14 | cout<<"[ "; 15 | Elem *head = list->head; 16 | while(head){ 17 | cout<data<<" "; 18 | head = head->next; 19 | } 20 | cout<<"]"<next = NULL; 25 | if(!(list->head)){ 26 | list->head = toAdd; 27 | return; 28 | } 29 | Elem *cur = list->head; 30 | while(cur->next){ 31 | cur = cur->next; 32 | } 33 | cur->next = toAdd; 34 | } 35 | 36 | Elem* newElem(int data, Elem *next = NULL){ 37 | Elem *cur = new Elem; 38 | cur->data = data; 39 | cur->next = next; 40 | return cur; 41 | } 42 | 43 | List *newList(Elem *elem = NULL){ 44 | List *list = new List; 45 | list->head = elem; 46 | return list; 47 | } 48 | 49 | void rmElem(List *list, int val){ 50 | Elem *cur, *prev; 51 | cur = list->head; 52 | prev = NULL; 53 | 54 | while(cur && cur->data != val){ 55 | prev = cur; 56 | cur = cur->next; 57 | } 58 | if(!cur){return;} 59 | if(!prev){ 60 | list->head = cur->next; 61 | delete cur; 62 | return; 63 | } 64 | prev->next = cur->next; 65 | delete cur; 66 | 67 | } 68 | 69 | void swap(Elem *a_prev, Elem *b_prev){ 70 | Elem *a = a_prev->next; 71 | Elem *b = b_prev->next; 72 | Elem *b_next = b->next; 73 | b->next = a->next; 74 | if(a->next == b){ 75 | b->next = a; 76 | a->next = b_next; 77 | a_prev->next = b; 78 | return; 79 | } 80 | a->next = b_next; 81 | a_prev->next = b; 82 | b_prev->next = a; 83 | } 84 | 85 | void sort(List *list){ 86 | Elem *a = list->head; 87 | Elem *b = a->next; 88 | int swap_count = 0; 89 | do{ 90 | swap_count = 0; 91 | a = list->head; 92 | b = a->next; 93 | while(b->next){ 94 | if(a->next->data > b->next->data){ 95 | swap(a,b); 96 | swap_count++; 97 | b = a->next; 98 | a = b; 99 | } else{ 100 | a = b; 101 | b = b->next; 102 | } 103 | } 104 | }while(swap_count); 105 | } 106 | 107 | int main(){ 108 | List *list = newList(); 109 | Elem* arr[] = { newElem(60), 110 | newElem(50), 111 | newElem(40), 112 | newElem(30), 113 | newElem(20), 114 | newElem(10)}; 115 | for(int i=0; i 2 | #include 3 | #include 4 | 5 | typedef struct Node{ 6 | int a; 7 | struct Node *next; 8 | } Node; 9 | 10 | typedef struct List{ 11 | Node *head; 12 | } List; 13 | 14 | List createList(int n){ 15 | List list = {NULL}; 16 | for(int i=0; ia = rand()%100+1; 19 | cur->next = list.head; 20 | list.head = cur; 21 | } 22 | return list; 23 | } 24 | 25 | void printList(List list){ 26 | Node *tmp = list.head; 27 | while(tmp){ 28 | printf("%d ", tmp->a); 29 | tmp = tmp->next; 30 | } 31 | printf("\n"); 32 | } 33 | 34 | int cmp(Node *a, Node *b){ 35 | if(b == NULL){ 36 | return -1; 37 | } 38 | if(a->a > b->a) 39 | return 1; 40 | if(a->a < b->a) 41 | return -1; 42 | return 0; 43 | } 44 | 45 | void swap(Node *a, Node *b, Node *prev_a, List *list){ 46 | a->next = b->next; 47 | b->next = a; 48 | if(prev_a) //comon 49 | prev_a->next = b; 50 | else//head 51 | list->head = b; 52 | 53 | } 54 | 55 | void sortList(List *list){ 56 | if(!list->head) 57 | return; 58 | while(1){ 59 | int swapCount = 0; 60 | Node *tmp = list->head; 61 | Node *prev = NULL; 62 | while(tmp){ 63 | if(cmp(tmp, tmp->next)>0){ //swap 64 | swapCount++; 65 | Node *next = tmp->next; 66 | swap(tmp, tmp->next, prev, list); 67 | prev = next; 68 | } else { 69 | prev = tmp; 70 | tmp=tmp->next; 71 | } 72 | } 73 | if(!swapCount) 74 | return; 75 | } 76 | } 77 | 78 | int main(){ 79 | srand(time(NULL)); 80 | List list = createList(5); 81 | printList(list); 82 | list.head->a = 1000; 83 | sortList(&list); 84 | printList(list); 85 | 86 | return 0; 87 | } 88 | -------------------------------------------------------------------------------- /lectures/list_22_march_21.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef struct Elem{ 5 | int data; 6 | struct Elem* next; 7 | } Elem; 8 | 9 | 10 | void printList(struct Elem *head){ 11 | while(head){ 12 | printf("%d ", head->data); 13 | head = head->next; 14 | } 15 | printf("\n"); 16 | } 17 | 18 | 19 | struct Elem* createElem(int data, struct Elem* next){ 20 | struct Elem *cur = (Elem*) malloc(sizeof(struct Elem)); 21 | cur->data = data; 22 | cur->next = next; 23 | return cur; 24 | } 25 | 26 | void append(struct Elem* head, int data){ 27 | while(head->next != NULL) 28 | head = head->next; 29 | struct Elem* cur = createElem(data, NULL); 30 | head->next = cur; 31 | } 32 | 33 | void insert(struct Elem* head, int val, int new_val){ 34 | while(head->data!=val){ 35 | head = head ->next; 36 | } 37 | struct Elem* cur = createElem(new_val, head->next); 38 | head->next = cur; 39 | } 40 | 41 | 42 | void clear(struct Elem *head){ 43 | while(head!=NULL){ 44 | struct Elem *tmp = head->next; 45 | free(head); 46 | head = tmp; 47 | } 48 | } 49 | 50 | void removeElem(struct Elem *head, int val){ //count(head) >=2 51 | struct Elem *cur = head->next; 52 | struct Elem *prev = head; 53 | while(cur->data!=val){ 54 | prev = cur; 55 | cur = cur->next; 56 | } 57 | 58 | prev->next = cur->next; 59 | free(cur); 60 | 61 | } 62 | 63 | void pushFront(Elem **head, int val){ 64 | struct Elem* cur = createElem(val, *head); 65 | *head = cur; 66 | printList(*head); 67 | } 68 | 69 | void swap(Elem **head, Elem *a_prev, Elem *b_prev){ 70 | Elem* b = b_prev->next; 71 | Elem* a = *head; 72 | Elem* tmp = b->next; 73 | if(a_prev == NULL){ 74 | if(a->next == b){ 75 | b->next = a; 76 | } else { 77 | b->next = a->next; 78 | b_prev->next = a; 79 | } 80 | a->next = tmp; 81 | *head = b; 82 | return; 83 | } 84 | a = a_prev->next; 85 | if(b_prev == a){ 86 | a_prev->next = b; 87 | b->next = a; 88 | a->next = tmp; 89 | return; 90 | } 91 | b->next = a->next; 92 | a->next = tmp; 93 | tmp = b_prev->next; 94 | b_prev->next = a_prev->next; 95 | a_prev->next = tmp; 96 | } 97 | 98 | void swap_usr(Elem **head, int a, int b){ 99 | Elem *cur = *head; 100 | Elem *a_prev = NULL; 101 | Elem *b_prev = NULL; 102 | while(cur->next){ 103 | if(cur->next->data == a) 104 | a_prev = cur; 105 | if(cur->next->data == b) 106 | b_prev = cur; 107 | cur = cur->next; 108 | } 109 | swap(head, a_prev, b_prev); 110 | } 111 | 112 | void sort(Elem **head){ 113 | Elem *cur = *head; 114 | Elem *cur_prev = NULL; 115 | while(cur){ 116 | if(cur->data > cur->next->data){ 117 | swap(head, cur_prev, cur); 118 | } 119 | cur_prev = cur; 120 | cur = cur->next; 121 | } 122 | } 123 | 124 | 125 | int main(){ 126 | struct Elem *head = createElem(1200, createElem(66, createElem(30, NULL))); 127 | append(head, -40); 128 | append(head, 500); 129 | append(head, 60); 130 | printList(head); 131 | 132 | //swap_usr(&head, 10, 60); 133 | 134 | printList(head); 135 | sort(&head); 136 | printList(head); 137 | 138 | clear(head); 139 | 140 | return 0; 141 | } 142 | -------------------------------------------------------------------------------- /lectures/list_based_stack.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef int type; 5 | 6 | struct Node{ 7 | type data; 8 | struct Node *next; 9 | }; 10 | 11 | struct Stack{ 12 | struct Node *head; 13 | int size; 14 | }; 15 | 16 | struct Stack stackInit(){ 17 | struct Stack stack={NULL, 0}; 18 | return stack; 19 | } 20 | 21 | void push(struct Stack *stack, type elem){ 22 | struct Node *node = malloc(sizeof(struct Node)); 23 | node->data = elem; 24 | node->next = stack->head; 25 | stack->head = node; 26 | stack->size++; 27 | } 28 | 29 | type pop(struct Stack *stack){ 30 | struct Node *node = stack->head; 31 | stack->head = stack->head->next; 32 | type res = node->data; 33 | free(node); 34 | stack->size--; 35 | return res; 36 | } 37 | 38 | int isEmpty(struct Stack *stack){ 39 | return !stack->size; 40 | } 41 | 42 | int main(){ 43 | 44 | struct Stack stack = stackInit(); 45 | 46 | push(&stack,10); 47 | push(&stack,20); 48 | push(&stack,30); 49 | 50 | while(!isEmpty(&stack)){ 51 | printf(">>%d\n",pop(&stack)); 52 | } 53 | 54 | return 0; 55 | } 56 | -------------------------------------------------------------------------------- /lectures/mim_ssprintscan.c: -------------------------------------------------------------------------------- 1 | #include 2 | // Что тут происходит? 1)скомпилится ли? 2)что выведет? 3 | 4 | 5 | int main(){ 6 | printf("A\n"); 7 | int a; 8 | printf(">%p\n", &a); 9 | int main(){ 10 | printf(">%p\n", &a); 11 | a = 1232; 12 | printf("AA\n"); 13 | char s[50]="3.14 512"; 14 | float f; 15 | int a; 16 | sscanf(s,"%f%d", &f, &a); 17 | sprintf(s, "%d %.1f", a,f); 18 | printf("%s\n",s); 19 | printf("BB\n"); 20 | return 0; 21 | } 22 | main(); 23 | printf("%d\n", a); 24 | printf("B\n"); 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /lectures/multidim_arrays/ex1.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | 5 | // one-dim array 6 | int secret_code[] = {1,2,3,4}; 7 | 8 | printf("secret_code[0]: %d\n", secret_code[0]); 9 | 10 | // sec-dim arraym list-initialized 11 | int disp[2][4] = { 12 | {10, 11, 12, 13}, 13 | {14, 15, 16, 17} 14 | }; 15 | 16 | printf("disp[0][0]: %d\n", disp[0][0]); 17 | 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /lectures/multidim_arrays/ex2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main() { 5 | 6 | // одномерный динамический массив 7 | int* secret_code_flatten = (int *)calloc(8, sizeof(int)); 8 | 9 | secret_code_flatten[3] = 3; 10 | 11 | printf("Flatten[0]: %d\n", secret_code_flatten[0]); 12 | printf("Flatten[3]: %d\n", secret_code_flatten[3]); 13 | 14 | // двумерный динамический массив 15 | int** secret_code_double = (int **)calloc(2, sizeof(int*)); 16 | 17 | printf("Double[0]: %p\n", secret_code_double[0]); 18 | 19 | 20 | for(int i=0; i < 2; i++) { 21 | secret_code_double[i] = (int*)calloc(4, sizeof(int)); 22 | secret_code_double[i][0] = 6; 23 | secret_code_double[i][2] = 4; 24 | } 25 | 26 | printf("_________________________________\n"); 27 | printf("Double[0][2]: %d\n", secret_code_double[0][2]); 28 | printf("Double[1][2]: %d\n", secret_code_double[1][2]); 29 | 30 | // освобождение памяти, куда же без него 31 | for(int i=0; i < 2; i++) 32 | free(secret_code_double[i]); 33 | free(secret_code_double); 34 | 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /lectures/multidim_arrays/ex3.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define SIZE 4 6 | 7 | void print_2darr(char** a, int size) { 8 | printf("ARRAY PRINT:\n"); 9 | for(int i=0; i 2 | #include 3 | 4 | #define I 2 5 | #define J 4 6 | #define K 6 7 | 8 | int main () 9 | { 10 | 11 | int mtrx[2][2] = {{1,1}, {2,2}}; 12 | 13 | // статический 3d массив 14 | int array[I][J][K]; 15 | int i, k, n, c; 16 | for (i=0; i 2 | #include 3 | #include 4 | #include 5 | 6 | // how many letters 1 block wil contain 7 | #define BUFF_SZ 100 8 | 9 | // how many BLOCKS text contains 10 | #define TEXT_BLOCKS 10 11 | 12 | int main() 13 | { 14 | // allocate memory for 1 block 15 | char** text=calloc(TEXT_BLOCKS,sizeof(char*)); 16 | char c; 17 | 18 | // main loop, each time geting letter from stdin. You can use another loop break condition instead "\n", EOF for e.g 19 | while((c=getchar())!='\n') 20 | { 21 | // here you need to fill up "text" by blocks of chars that you read from stdin and extend "text" 22 | 23 | // do the work 24 | } 25 | 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /lectures/numStorage.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define N 100 4 | 5 | void debugStrPrint(char *s){ 6 | for(int i=0; s[i]; i++) 7 | printf("[%c](%d)\n", s[i], s[i]); 8 | } 9 | 10 | void printMenu(){ 11 | char s[100] = "\n0 - Exit\n" 12 | "1 - print storage\n" 13 | "2 - add number\n" 14 | "3 - clear"; 15 | //debugStrPrint(s); 16 | printf("%s\n", s); 17 | } 18 | 19 | void addToArr(int *arr, int *n, int elem){ 20 | arr[*n] = elem; 21 | (*n)++; 22 | } 23 | 24 | int main(){ 25 | int arr[N]; 26 | int n = 0; 27 | printf("Before:\n"); 28 | for(int i=0; i1\n"); 48 | break; 49 | case 2: 50 | printf(">2\n"); 51 | break; 52 | default: 53 | printf("Try again\n"); 54 | } 55 | } 56 | return 0; 57 | } 58 | -------------------------------------------------------------------------------- /lectures/num_storage/Makefile: -------------------------------------------------------------------------------- 1 | FLAGS=-Wall 2 | 3 | all: main.o debug.o storage.o 4 | gcc $(FLAGS) main.o debug.o storage.o 5 | 6 | main.o: main.c debug.h storage.h 7 | gcc -c main.c 8 | 9 | debug.o: debug.c debug.h 10 | gcc -c debug.c 11 | 12 | storage.o: storage.c storage.h 13 | gcc -c storage.c 14 | 15 | clean: 16 | rm *.o 17 | -------------------------------------------------------------------------------- /lectures/num_storage/debug.c: -------------------------------------------------------------------------------- 1 | #include "debug.h" 2 | 3 | void debugStrPrint(char *s){ 4 | for(int i=0; s[i]; i++) 5 | printf("[%c](%d)\n", s[i], s[i]); 6 | } 7 | 8 | -------------------------------------------------------------------------------- /lectures/num_storage/debug.h: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void debugStrPrint(char *s); 4 | 5 | -------------------------------------------------------------------------------- /lectures/num_storage/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "storage.h" 3 | #include "debug.h" 4 | 5 | #define N 100 6 | 7 | void printMenu(){ 8 | char s[100] = "\n0 - Exit\n" 9 | "1 - print storage\n" 10 | "2 - add number\n" 11 | "3 - clear"; 12 | //debugStrPrint(s); 13 | printf("%s\n", s); 14 | } 15 | 16 | int main(){ 17 | printf(STR); 18 | int arr[N]; 19 | int n = 0; 20 | //addToArr(arr, &n, 10); //&arr[0] 21 | printf("Hello, User!\n\n"); 22 | int choice; 23 | while(1){ //for(;;) 24 | printMenu(); 25 | scanf("%d", &choice); 26 | switch(choice){ 27 | case 0: 28 | printf("I will miss you...\n"); 29 | return 0; 30 | case 1: 31 | printArr(arr,n); 32 | break; 33 | case 2: 34 | printf("> Enter number: "); 35 | int numb; 36 | scanf("%d", &numb); 37 | addToArr(arr, &n, numb); 38 | break; 39 | default: 40 | printf("Try again\n"); 41 | } 42 | } 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /lectures/num_storage/storage.c: -------------------------------------------------------------------------------- 1 | #include "storage.h" 2 | 3 | void addToArr(int *arr, int *n, int elem){ 4 | arr[*n] = elem; 5 | (*n)++; 6 | printf(STR); 7 | } 8 | 9 | void printArr(int *arr, int n){ 10 | printf("["); 11 | for(int i=0; i 2 | 3 | #define STR "Hello from arr!!!!\n" 4 | 5 | void addToArr(int *arr, int *n, int elem); 6 | void printArr(int *arr, int n); 7 | -------------------------------------------------------------------------------- /lectures/polymorphic_printer.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int predicat(int a){ 5 | return a%2; 6 | } 7 | 8 | int summPred(int *a, int n, int(*pred)(int)){ 9 | int sum = 0; 10 | for(int i=0; i 2 | 3 | void printBin(char c){ 4 | unsigned char mask = 1<<(sizeof(char)*8-1); 5 | for(;mask;mask>>=1){ 6 | printf("%d", c&mask?1:0); 7 | } 8 | printf("\n"); 9 | } 10 | 11 | int main(){ 12 | signed char c = 123; 13 | c |= 1<<0; 14 | printBin(c); 15 | c &= ~(1<<3); 16 | printBin(c); 17 | printf("%d\n", c); 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /lectures/reading_sentences/main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "readSentence.h" 3 | 4 | int main() 5 | { 6 | char *s; 7 | while(s = readSentence()){ 8 | printf("[%s]\n", s); 9 | free(s); 10 | } 11 | 12 | return 0; 13 | } 14 | -------------------------------------------------------------------------------- /lectures/reading_sentences/readSentence.c: -------------------------------------------------------------------------------- 1 | #include "readSentence.h" 2 | 3 | char* readSentence(){ 4 | int size = INIT_SIZE; 5 | int length = 0; 6 | char *text = malloc(size*sizeof(char)); 7 | int c; 8 | 9 | while ((c = getchar()) != '\n'){ 10 | text[length++]=c; 11 | if(length == size){ 12 | size += DELTA; 13 | text = realloc(text, size); 14 | } 15 | if(c == '.') 16 | break; 17 | } 18 | 19 | if(length>0){ 20 | text[length]='\0'; 21 | return text; 22 | } 23 | else{ 24 | free(text); 25 | return NULL; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /lectures/reading_sentences/readSentence.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | #include 5 | 6 | #define INIT_SIZE 50 7 | #define DELTA 50 8 | 9 | char* readSentence(); 10 | -------------------------------------------------------------------------------- /lectures/recursion+tree/Readme: -------------------------------------------------------------------------------- 1 | mathTreeMain - Обход дерева 2 | f1f2 - глубина рекурсии от размера аргументов 3 | factorial - рекурсивная/итеративная версия 4 | lagreTreeMain - время и память при обходе дерева 5 | SumExample - сумма (+оптимизация) 6 | opt - оптимизация 7 | -------------------------------------------------------------------------------- /lectures/recursion+tree/arrayStack.c: -------------------------------------------------------------------------------- 1 | #include "arrayStack.h" 2 | 3 | int isStackEmpty() 4 | { 5 | if(stackTop == -1) 6 | return 1; 7 | else 8 | return 0; 9 | } 10 | 11 | void pushStack(TYPE item) 12 | { 13 | stackTop++; 14 | stackArr[stackTop] = item; 15 | } 16 | 17 | TYPE popStack() 18 | { 19 | TYPE item = stackArr[stackTop]; 20 | stackTop--; 21 | return item; 22 | } 23 | -------------------------------------------------------------------------------- /lectures/recursion+tree/arrayStack.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define TYPE struct node * 5 | 6 | struct node; 7 | 8 | static TYPE stackArr[1000]; 9 | static int stackTop = -1; 10 | 11 | int isStackEmpty(); 12 | 13 | void pushStack(TYPE item); 14 | 15 | TYPE popStack(); 16 | -------------------------------------------------------------------------------- /lectures/recursion+tree/asmEspExample.c: -------------------------------------------------------------------------------- 1 | // using stack depending on the parameters 2 | 3 | #include 4 | #include 5 | 6 | int baseESP; 7 | 8 | int getESP() 9 | { 10 | unsigned int esp; 11 | __asm__ ( "movl %%esp, %0\n" 12 | :"=r"(esp) /* выходные операнды */ 13 | : /* входные операнды */ 14 | : /* разрушаемые регистры */ 15 | ); 16 | return esp; 17 | } 18 | 19 | struct data 20 | { 21 | int a[10]; 22 | }; 23 | 24 | void f(int a) 25 | { 26 | //int arr[100]; 27 | printf("%d\n",baseESP - getESP()); 28 | } 29 | 30 | void f1(struct data d) 31 | { 32 | printf("%d\n",baseESP - getESP()); 33 | } 34 | 35 | void f3() 36 | { 37 | printf("%d\n",baseESP - getESP()); 38 | } 39 | 40 | int main() 41 | { 42 | struct data d; 43 | 44 | baseESP = getESP(); 45 | f(10); 46 | f1(d); 47 | f3(); 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /lectures/recursion+tree/f1f2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | //sizeof parameters 7 | //other calls 8 | 9 | struct S{ 10 | double s[100]; 11 | }; 12 | 13 | struct S1{ 14 | char c[100]; 15 | }; 16 | 17 | void f(struct S s, int i){ 18 | //printf("%d ",i); 19 | if(i>0) 20 | f(s,--i); 21 | } 22 | 23 | void f1(struct S1 c, int i){ 24 | // printf("%d ",i); 25 | if(i>0) 26 | f1(c,--i); 27 | } 28 | 29 | int main() 30 | { 31 | 32 | struct S s; 33 | struct S1 s1; 34 | printf("%lu, %lu\n", sizeof(char), sizeof(double)); 35 | f (s, 10000); 36 | //f1(s1,60000); 37 | printf("sizeof(S1) = %lu\n", sizeof(struct S1)); 38 | printf("sizeof(S1) = %lu\n", sizeof(struct S)); 39 | // f1(s1,58000); 40 | 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /lectures/recursion+tree/factorial.c: -------------------------------------------------------------------------------- 1 | // using stack in the calculation of the factorial 2 | 3 | #include 4 | 5 | 6 | int baseESP; 7 | int maxESPOffset = 0; 8 | 9 | int getESP() 10 | { 11 | unsigned int esp; 12 | __asm__ ( "movl %%esp, %0\n" 13 | :"=r"(esp) /* выходные операнды */ 14 | : /* входные операнды */ 15 | : /* разрушаемые регистры */ 16 | ); 17 | return esp; 18 | } 19 | 20 | int recFact(int n) 21 | { 22 | int curEsp = getESP(); 23 | if(baseESP - curEsp > maxESPOffset) 24 | maxESPOffset = baseESP - curEsp; 25 | 26 | if(n<=0) 27 | return 1; 28 | return n * recFact(n-1); 29 | } 30 | 31 | int iterFact(int n) 32 | { 33 | maxESPOffset = baseESP - getESP(); 34 | int prod = 1; 35 | for(int i=2;i<=n;i++) 36 | prod*=i; 37 | return prod; 38 | } 39 | 40 | int main() 41 | { 42 | int res, n = 10; 43 | baseESP = getESP(); 44 | maxESPOffset = 0; 45 | res = recFact(n); 46 | printf("res:%d max esp offset:%d\n", res,maxESPOffset); 47 | 48 | maxESPOffset = 0; 49 | res = iterFact(n); 50 | printf("res:%d max esp offset:%d\n", res,maxESPOffset); 51 | } 52 | -------------------------------------------------------------------------------- /lectures/recursion+tree/factorial.s: -------------------------------------------------------------------------------- 1 | .file "factorial.c" 2 | .section .text.unlikely,"ax",@progbits 3 | .LCOLDB0: 4 | .text 5 | .LHOTB0: 6 | .p2align 4,,15 7 | .globl getESP 8 | .type getESP, @function 9 | getESP: 10 | .LFB23: 11 | .cfi_startproc 12 | #APP 13 | # 12 "factorial.c" 1 14 | movl %esp, %eax 15 | 16 | # 0 "" 2 17 | #NO_APP 18 | ret 19 | .cfi_endproc 20 | .LFE23: 21 | .size getESP, .-getESP 22 | .section .text.unlikely 23 | .LCOLDE0: 24 | .text 25 | .LHOTE0: 26 | .section .text.unlikely 27 | .LCOLDB1: 28 | .text 29 | .LHOTB1: 30 | .p2align 4,,15 31 | .globl recFact 32 | .type recFact, @function 33 | recFact: 34 | .LFB24: 35 | .cfi_startproc 36 | pushl %ebp 37 | .cfi_def_cfa_offset 8 38 | .cfi_offset 5, -8 39 | movl baseESP, %ebp 40 | movl $1, %eax 41 | pushl %edi 42 | .cfi_def_cfa_offset 12 43 | .cfi_offset 7, -12 44 | pushl %esi 45 | .cfi_def_cfa_offset 16 46 | .cfi_offset 6, -16 47 | xorl %edi, %edi 48 | movl maxESPOffset, %esi 49 | pushl %ebx 50 | .cfi_def_cfa_offset 20 51 | .cfi_offset 3, -20 52 | #APP 53 | # 12 "factorial.c" 1 54 | movl %esp, %ecx 55 | 56 | # 0 "" 2 57 | #NO_APP 58 | subl %ecx, %ebp 59 | movl 20(%esp), %edx 60 | movl %esi, %ebx 61 | movl %ebp, %ecx 62 | jmp .L5 63 | .p2align 4,,10 64 | .p2align 3 65 | .L13: 66 | imull %edx, %eax 67 | subl $1, %edx 68 | .L5: 69 | cmpl %ebx, %ecx 70 | jle .L3 71 | movl %ecx, %esi 72 | movl %ecx, %ebx 73 | movl $1, %edi 74 | .L3: 75 | testl %edx, %edx 76 | jg .L13 77 | movl %edi, %ebx 78 | testb %bl, %bl 79 | jne .L14 80 | .L6: 81 | popl %ebx 82 | .cfi_remember_state 83 | .cfi_restore 3 84 | .cfi_def_cfa_offset 16 85 | popl %esi 86 | .cfi_restore 6 87 | .cfi_def_cfa_offset 12 88 | popl %edi 89 | .cfi_restore 7 90 | .cfi_def_cfa_offset 8 91 | popl %ebp 92 | .cfi_restore 5 93 | .cfi_def_cfa_offset 4 94 | ret 95 | .L14: 96 | .cfi_restore_state 97 | movl %esi, maxESPOffset 98 | jmp .L6 99 | .cfi_endproc 100 | .LFE24: 101 | .size recFact, .-recFact 102 | .section .text.unlikely 103 | .LCOLDE1: 104 | .text 105 | .LHOTE1: 106 | .section .text.unlikely 107 | .LCOLDB2: 108 | .text 109 | .LHOTB2: 110 | .p2align 4,,15 111 | .globl iterFact 112 | .type iterFact, @function 113 | iterFact: 114 | .LFB25: 115 | .cfi_startproc 116 | movl 4(%esp), %ecx 117 | movl baseESP, %edx 118 | #APP 119 | # 12 "factorial.c" 1 120 | movl %esp, %eax 121 | 122 | # 0 "" 2 123 | #NO_APP 124 | subl %eax, %edx 125 | cmpl $1, %ecx 126 | movl %edx, maxESPOffset 127 | jle .L18 128 | addl $1, %ecx 129 | movl $2, %edx 130 | movl $1, %eax 131 | .p2align 4,,10 132 | .p2align 3 133 | .L17: 134 | imull %edx, %eax 135 | addl $1, %edx 136 | cmpl %ecx, %edx 137 | jne .L17 138 | rep ret 139 | .L18: 140 | movl $1, %eax 141 | ret 142 | .cfi_endproc 143 | .LFE25: 144 | .size iterFact, .-iterFact 145 | .section .text.unlikely 146 | .LCOLDE2: 147 | .text 148 | .LHOTE2: 149 | .section .rodata.str1.1,"aMS",@progbits,1 150 | .LC3: 151 | .string "res:%d max esp offset:%d\n" 152 | .section .text.unlikely 153 | .LCOLDB4: 154 | .section .text.startup,"ax",@progbits 155 | .LHOTB4: 156 | .p2align 4,,15 157 | .globl main 158 | .type main, @function 159 | main: 160 | .LFB26: 161 | .cfi_startproc 162 | leal 4(%esp), %ecx 163 | .cfi_def_cfa 1, 0 164 | andl $-16, %esp 165 | #APP 166 | # 12 "factorial.c" 1 167 | movl %esp, %eax 168 | 169 | # 0 "" 2 170 | #NO_APP 171 | pushl -4(%ecx) 172 | pushl %ebp 173 | .cfi_escape 0x10,0x5,0x2,0x75,0 174 | movl %esp, %ebp 175 | pushl %esi 176 | .cfi_escape 0x10,0x6,0x2,0x75,0x7c 177 | movl %eax, %esi 178 | pushl %ebx 179 | pushl %ecx 180 | .cfi_escape 0xf,0x3,0x75,0x74,0x6 181 | .cfi_escape 0x10,0x3,0x2,0x75,0x78 182 | xorl %ebx, %ebx 183 | #APP 184 | # 12 "factorial.c" 1 185 | movl %esp, %ecx 186 | 187 | # 0 "" 2 188 | #NO_APP 189 | subl %ecx, %esi 190 | subl $12, %esp 191 | movl %eax, baseESP 192 | cmpl %esi, %ebx 193 | movl $0, maxESPOffset 194 | jl .L36 195 | xorl %edx, %edx 196 | movl %ebx, %ecx 197 | .L24: 198 | movl %eax, %esi 199 | #APP 200 | # 12 "factorial.c" 1 201 | movl %esp, %ebx 202 | 203 | # 0 "" 2 204 | #NO_APP 205 | subl %ebx, %esi 206 | cmpl %esi, %ecx 207 | movl %esi, %ebx 208 | jl .L37 209 | movl %ecx, %ebx 210 | .L25: 211 | movl %eax, %esi 212 | #APP 213 | # 12 "factorial.c" 1 214 | movl %esp, %ecx 215 | 216 | # 0 "" 2 217 | #NO_APP 218 | subl %ecx, %esi 219 | cmpl %esi, %ebx 220 | movl %esi, %ecx 221 | jl .L38 222 | movl %ebx, %ecx 223 | .L26: 224 | movl %eax, %esi 225 | #APP 226 | # 12 "factorial.c" 1 227 | movl %esp, %ebx 228 | 229 | # 0 "" 2 230 | #NO_APP 231 | subl %ebx, %esi 232 | cmpl %esi, %ecx 233 | movl %esi, %ebx 234 | jl .L39 235 | movl %ecx, %ebx 236 | .L27: 237 | movl %eax, %esi 238 | #APP 239 | # 12 "factorial.c" 1 240 | movl %esp, %ecx 241 | 242 | # 0 "" 2 243 | #NO_APP 244 | subl %ecx, %esi 245 | cmpl %esi, %ebx 246 | movl %esi, %ecx 247 | jl .L40 248 | movl %ebx, %ecx 249 | .L28: 250 | movl %eax, %esi 251 | #APP 252 | # 12 "factorial.c" 1 253 | movl %esp, %ebx 254 | 255 | # 0 "" 2 256 | #NO_APP 257 | subl %ebx, %esi 258 | cmpl %esi, %ecx 259 | movl %esi, %ebx 260 | jl .L41 261 | movl %ecx, %ebx 262 | .L29: 263 | movl %eax, %esi 264 | #APP 265 | # 12 "factorial.c" 1 266 | movl %esp, %ecx 267 | 268 | # 0 "" 2 269 | #NO_APP 270 | subl %ecx, %esi 271 | cmpl %esi, %ebx 272 | movl %esi, %ecx 273 | jl .L42 274 | movl %ebx, %ecx 275 | .L30: 276 | #APP 277 | # 12 "factorial.c" 1 278 | movl %esp, %ebx 279 | 280 | # 0 "" 2 281 | #NO_APP 282 | subl %ebx, %eax 283 | cmpl %ecx, %eax 284 | jle .L47 285 | .L31: 286 | movl %eax, maxESPOffset 287 | movl %eax, %ecx 288 | .L32: 289 | pushl %ecx 290 | pushl $3628800 291 | pushl $.LC3 292 | pushl $1 293 | call __printf_chk 294 | movl baseESP, %edx 295 | #APP 296 | # 12 "factorial.c" 1 297 | movl %esp, %eax 298 | 299 | # 0 "" 2 300 | #NO_APP 301 | subl %eax, %edx 302 | pushl %edx 303 | pushl $3628800 304 | pushl $.LC3 305 | pushl $1 306 | movl %edx, maxESPOffset 307 | call __printf_chk 308 | addl $32, %esp 309 | leal -12(%ebp), %esp 310 | xorl %eax, %eax 311 | popl %ecx 312 | .cfi_remember_state 313 | .cfi_restore 1 314 | .cfi_def_cfa 1, 0 315 | popl %ebx 316 | .cfi_restore 3 317 | popl %esi 318 | .cfi_restore 6 319 | popl %ebp 320 | .cfi_restore 5 321 | leal -4(%ecx), %esp 322 | .cfi_def_cfa 4, 4 323 | ret 324 | .L47: 325 | .cfi_restore_state 326 | testb %dl, %dl 327 | je .L32 328 | movl %ecx, %eax 329 | jmp .L31 330 | .L42: 331 | movl $1, %edx 332 | jmp .L30 333 | .L41: 334 | movl $1, %edx 335 | jmp .L29 336 | .L40: 337 | movl $1, %edx 338 | jmp .L28 339 | .L39: 340 | movl $1, %edx 341 | jmp .L27 342 | .L38: 343 | movl $1, %edx 344 | jmp .L26 345 | .L37: 346 | movl $1, %edx 347 | jmp .L25 348 | .L36: 349 | movl %esi, %ecx 350 | movl $1, %edx 351 | jmp .L24 352 | .cfi_endproc 353 | .LFE26: 354 | .size main, .-main 355 | .section .text.unlikely 356 | .LCOLDE4: 357 | .section .text.startup 358 | .LHOTE4: 359 | .globl maxESPOffset 360 | .bss 361 | .align 4 362 | .type maxESPOffset, @object 363 | .size maxESPOffset, 4 364 | maxESPOffset: 365 | .zero 4 366 | .comm baseESP,4,4 367 | .ident "GCC: (Ubuntu 5.4.0-6ubuntu1~16.04.10) 5.4.0 20160609" 368 | .section .note.GNU-stack,"",@progbits 369 | -------------------------------------------------------------------------------- /lectures/recursion+tree/largeTreeMain.c: -------------------------------------------------------------------------------- 1 | // Counting memory and time while searching in a large tree 2 | 3 | #include 4 | #include 5 | #include 6 | #include "arrayStack.h" 7 | 8 | int baseESP; 9 | int maxESPOffset = 0; 10 | 11 | int getESP() 12 | { 13 | unsigned int esp; 14 | __asm__ ( "movl %%esp, %0\n" 15 | :"=r"(esp) /* выходные операнды */ 16 | : /* входные операнды */ 17 | : /* разрушаемые регистры */ 18 | ); 19 | return esp; 20 | } 21 | 22 | struct node 23 | { 24 | int data; 25 | struct node *left; 26 | struct node *right; 27 | }; 28 | 29 | struct node* createNode(int a, struct node *left, struct node *right) 30 | { 31 | struct node *cur = malloc(sizeof(struct node)); 32 | cur->left = left; 33 | cur->right = right; 34 | cur->data = a; 35 | return cur; 36 | } 37 | 38 | struct node* createLeaf(int a) 39 | { 40 | return createNode(a,NULL,NULL); 41 | } 42 | 43 | struct node* generateTree(int depth) 44 | { 45 | if(depth==0) 46 | return createLeaf(rand()%10); 47 | return createNode((rand()%10),NULL,generateTree(depth-1)); 48 | 49 | 50 | } 51 | 52 | void printTreeRec(struct node* root) 53 | { 54 | if(root == NULL) 55 | return; 56 | if(root->left!=NULL) 57 | { 58 | printf("("); 59 | printTreeRec(root->left); 60 | printf(")"); 61 | } 62 | printf("%d",root->data); 63 | if(root->right!=NULL) 64 | { 65 | printf("("); 66 | printTreeRec(root->right); 67 | printf(")"); 68 | } 69 | } 70 | 71 | int recSum(struct node* root) 72 | { 73 | 74 | int curEsp = getESP(); 75 | if(baseESP - curEsp > maxESPOffset) 76 | maxESPOffset = baseESP - curEsp; 77 | 78 | if(root == NULL) 79 | return 0; 80 | return root->data + recSum(root->left) + recSum(root->right); 81 | } 82 | 83 | int iterSum(struct node* root) 84 | { 85 | maxESPOffset = baseESP - getESP();// + call from this func (push, pop, etc.) 86 | int sum = 0; 87 | struct node* cur = root; 88 | pushStack(cur); 89 | while(!isStackEmpty()) 90 | { 91 | cur = popStack(); 92 | sum+=cur->data; 93 | if(cur->left!=NULL) 94 | pushStack(cur->left); 95 | if(cur->right!=NULL) 96 | pushStack(cur->right); 97 | } 98 | return sum; 99 | } 100 | 101 | int main() 102 | { 103 | 104 | struct node* root; 105 | clock_t time; 106 | root = generateTree(25000); 107 | printf("generated\n"); 108 | //printTreeRec(root); 109 | printf("\n"); 110 | 111 | baseESP = getESP(); 112 | maxESPOffset = 0; 113 | time = clock(); 114 | recSum(root); 115 | //printf("%d\n",recSum(root)); 116 | time = clock() - time; 117 | printf("time: %ld Max esp offset: %d\n", time, maxESPOffset); 118 | 119 | maxESPOffset = 0; 120 | time = clock(); 121 | iterSum(root); 122 | //printf("%d\n",iterSum(root)); 123 | time = clock() - time; 124 | printf("time: %ld Max esp offset: %d\n", time, maxESPOffset); 125 | 126 | 127 | 128 | return 0; 129 | } 130 | -------------------------------------------------------------------------------- /lectures/recursion+tree/mathTreeMain.c: -------------------------------------------------------------------------------- 1 | // Example of working with a tree. Recursive and iterative printing 2 | 3 | #include 4 | #include 5 | #include "stack.h" 6 | 7 | union data 8 | { 9 | int n; 10 | char c; 11 | }; 12 | 13 | struct node 14 | { 15 | int flag; //0 - node, 1 - leaf 16 | union data data; 17 | struct node *left; 18 | struct node *right; 19 | }; 20 | 21 | void foo(struct node* root) 22 | { //Что делает функция?? 23 | struct node* cur = root; 24 | while(!isStackEmpty() || cur!=NULL) 25 | { 26 | if(!isStackEmpty()) 27 | { 28 | cur = popStack(); 29 | if(cur->flag) 30 | printf("%d",cur->data.n); 31 | else 32 | printf(" %c ",cur->data.c); 33 | if(cur->right!=NULL) 34 | cur = cur->right; 35 | else 36 | cur = NULL; 37 | } 38 | while(cur!=NULL) 39 | { 40 | pushStack(cur); 41 | cur = cur->left; 42 | } 43 | } 44 | } 45 | 46 | struct node* createNode(char c, struct node *left, struct node *right) 47 | { 48 | struct node *cur = malloc(sizeof(struct node)); 49 | cur->left = left; 50 | cur->right = right; 51 | cur->flag = 0; 52 | cur->data.c = c; 53 | return cur; 54 | } 55 | 56 | struct node* createLeaf(int n) 57 | { 58 | struct node *cur = malloc(sizeof(struct node)); 59 | cur->left = cur->right = NULL; 60 | cur->flag = 1; 61 | cur->data.n = n; 62 | return cur; 63 | } 64 | 65 | void printTreeRec(struct node* root) 66 | { 67 | if(root == NULL) 68 | return; 69 | if(root->flag) 70 | { 71 | printf("%d",root->data.n); 72 | return; 73 | } 74 | printf("("); 75 | printTreeRec(root->left); 76 | printf(")"); 77 | printf(" %c ",root->data.c); 78 | printf("("); 79 | printTreeRec(root->right); 80 | printf(")"); 81 | } 82 | 83 | void printTreeIter(struct node* root) 84 | { 85 | struct node* cur = root; 86 | while(!isStackEmpty() || cur!=NULL) 87 | { 88 | if(!isStackEmpty()) 89 | { 90 | cur = popStack(); 91 | if(cur->flag) 92 | printf("%d",cur->data.n); 93 | else 94 | printf(" %c ",cur->data.c); 95 | if(cur->right!=NULL) 96 | cur = cur->right; 97 | else 98 | cur = NULL; 99 | } 100 | while(cur!=NULL) 101 | { 102 | pushStack(cur); 103 | cur = cur->left; 104 | } 105 | } 106 | } 107 | 108 | int main() 109 | { 110 | 111 | struct node* root; 112 | //root = createNode('+',createNode('-',createLeaf(10),createLeaf(7)),createLeaf(15)); 113 | root = createNode('+',createNode('-',createLeaf(10),createLeaf(7)),createNode('+',createLeaf(3),createLeaf(33))); 114 | printTreeRec(root); 115 | printf("\n"); 116 | printTreeIter(root); 117 | 118 | 119 | return 0; 120 | } 121 | -------------------------------------------------------------------------------- /lectures/recursion+tree/opt.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void f(int n){ 4 | if(n<=0) 5 | return; 6 | puts("hello"); 7 | f(n-1); 8 | } 9 | 10 | int main(){ 11 | f(6); 12 | 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /lectures/recursion+tree/opt.s: -------------------------------------------------------------------------------- 1 | .file "opt.c" 2 | .section .rodata.str1.1,"aMS",@progbits,1 3 | .LC0: 4 | .string "hello" 5 | .section .text.unlikely,"ax",@progbits 6 | .LCOLDB1: 7 | .text 8 | .LHOTB1: 9 | .p2align 4,,15 10 | .globl f 11 | .type f, @function 12 | f: 13 | .LFB23: 14 | .cfi_startproc 15 | pushl %ebx 16 | .cfi_def_cfa_offset 8 17 | .cfi_offset 3, -8 18 | subl $8, %esp 19 | .cfi_def_cfa_offset 16 20 | movl 16(%esp), %ebx 21 | testl %ebx, %ebx 22 | jle .L1 23 | .p2align 4,,10 24 | .p2align 3 25 | .L7: 26 | subl $12, %esp 27 | .cfi_def_cfa_offset 28 28 | pushl $.LC0 29 | .cfi_def_cfa_offset 32 30 | call puts 31 | addl $16, %esp 32 | .cfi_def_cfa_offset 16 33 | subl $1, %ebx 34 | jne .L7 35 | .L1: 36 | addl $8, %esp 37 | .cfi_def_cfa_offset 8 38 | popl %ebx 39 | .cfi_restore 3 40 | .cfi_def_cfa_offset 4 41 | ret 42 | .cfi_endproc 43 | .LFE23: 44 | .size f, .-f 45 | .section .text.unlikely 46 | .LCOLDE1: 47 | .text 48 | .LHOTE1: 49 | .section .text.unlikely 50 | .LCOLDB2: 51 | .section .text.startup,"ax",@progbits 52 | .LHOTB2: 53 | .p2align 4,,15 54 | .globl main 55 | .type main, @function 56 | main: 57 | .LFB24: 58 | .cfi_startproc 59 | leal 4(%esp), %ecx 60 | .cfi_def_cfa 1, 0 61 | andl $-16, %esp 62 | pushl -4(%ecx) 63 | pushl %ebp 64 | .cfi_escape 0x10,0x5,0x2,0x75,0 65 | movl %esp, %ebp 66 | pushl %ebx 67 | pushl %ecx 68 | .cfi_escape 0xf,0x3,0x75,0x78,0x6 69 | .cfi_escape 0x10,0x3,0x2,0x75,0x7c 70 | movl $6, %ebx 71 | .p2align 4,,10 72 | .p2align 3 73 | .L12: 74 | subl $12, %esp 75 | pushl $.LC0 76 | call puts 77 | addl $16, %esp 78 | subl $1, %ebx 79 | jne .L12 80 | leal -8(%ebp), %esp 81 | xorl %eax, %eax 82 | popl %ecx 83 | .cfi_restore 1 84 | .cfi_def_cfa 1, 0 85 | popl %ebx 86 | .cfi_restore 3 87 | popl %ebp 88 | .cfi_restore 5 89 | leal -4(%ecx), %esp 90 | .cfi_def_cfa 4, 4 91 | ret 92 | .cfi_endproc 93 | .LFE24: 94 | .size main, .-main 95 | .section .text.unlikely 96 | .LCOLDE2: 97 | .section .text.startup 98 | .LHOTE2: 99 | .ident "GCC: (Ubuntu 5.4.0-6ubuntu1~16.04.10) 5.4.0 20160609" 100 | .section .note.GNU-stack,"",@progbits 101 | -------------------------------------------------------------------------------- /lectures/recursion+tree/stack.c: -------------------------------------------------------------------------------- 1 | #include "stack.h" 2 | 3 | int isStackEmpty() 4 | { 5 | if(root == NULL) 6 | return 1; 7 | else 8 | return 0; 9 | } 10 | 11 | void pushStack(TYPE item) 12 | { 13 | struct stackNode * cur = malloc(sizeof(struct stackNode)); 14 | cur->item = item; 15 | cur->next = root; 16 | root = cur; 17 | } 18 | 19 | TYPE popStack() 20 | { 21 | struct stackNode * cur = root; 22 | root = cur->next; 23 | TYPE ret = cur->item; 24 | free(cur); 25 | return ret; 26 | } 27 | -------------------------------------------------------------------------------- /lectures/recursion+tree/stack.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define TYPE struct node * 5 | 6 | struct node; 7 | 8 | struct stackNode 9 | { 10 | TYPE item; 11 | struct stackNode *next; 12 | }; 13 | 14 | static struct stackNode *root = NULL; 15 | 16 | int isStackEmpty(); 17 | 18 | void pushStack(TYPE item); 19 | 20 | TYPE popStack(); 21 | -------------------------------------------------------------------------------- /lectures/recursion+tree/sumExample.c: -------------------------------------------------------------------------------- 1 | // Optimization summation 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | int recSum(int *a, int n) 10 | { 11 | if(n==0) 12 | return 0; 13 | return *(a+n-1) + recSum(a,n-1); 14 | } 15 | 16 | int iterSum(int *a, int n) 17 | { 18 | int sum = 0; 19 | int i; 20 | for(i=0;i 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | int recSum(int *a, int n) 10 | { 11 | if(n==0) 12 | return 0; 13 | return *(a+n-1) + recSum(a,n-1); 14 | } 15 | 16 | int iterSum(int *a, int n) 17 | { 18 | int sum = 0; 19 | int i; 20 | for(i=0;i 2 | #include 3 | #include 4 | 5 | 6 | int main () 7 | { 8 | char * regexString = "\\+?[[:digit:]][\\( ]?([[:digit:]]{3})[\\) ]?([[:digit:]]{3}.?[[:digit:]]{2}.?[[:digit:]]{2})"; 9 | size_t maxGroups = 3; 10 | 11 | regex_t regexCompiled; 12 | regmatch_t groupArray[maxGroups]; 13 | 14 | if (regcomp(®exCompiled, regexString, REG_EXTENDED)) 15 | { 16 | printf("Wowm no - can't compile regular expression\n"); 17 | return 0; 18 | }; 19 | 20 | FILE *f = fopen("inp.txt", "r"); 21 | if(!f){ 22 | printf("Wow, no - can't open file\n"); 23 | return 0; 24 | } 25 | char s[100]; 26 | while (fgets(s,100,f)){ 27 | printf("%s",s); 28 | if (regexec(®exCompiled, s, maxGroups, groupArray, 0) == 0) 29 | { 30 | printf("matched!\n"); 31 | for (int i = 0; i < maxGroups; i++) 32 | { 33 | if (groupArray[i].rm_so == -1) 34 | break; 35 | 36 | printf("Group %d: [%2d-%2d]: ", i, groupArray[i].rm_so, groupArray[i].rm_eo); 37 | for(int j=groupArray[i].rm_so;j 2 | #include 3 | #include 4 | 5 | void rmdigits(char *s){ 6 | for(int i=0; s[i];){ 7 | if(isdigit(s[i])){ 8 | memmove(&s[i], &s[i+1], strlen(&s[i])); 9 | // for(int j=i; s[j]; j++) 10 | // s[j] = s[j+1]; 11 | } else { 12 | i++; 13 | } 14 | } 15 | } 16 | 17 | int main(){ 18 | char s[100] = "abc123qweqw87ssd"; 19 | rmdigits(s); 20 | printf("%s\n", s); 21 | 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /lectures/return_local_address_mistake.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int * getValue(float v) 4 | { 5 | int value = (int )v; 6 | int *s = &value; 7 | return s; 8 | } 9 | 10 | void g() 11 | { 12 | char d[100]; 13 | for(int i=0;i<100;i++) 14 | d[i]=i; 15 | 16 | printf("%s\n",d); 17 | } 18 | 19 | int main() 20 | { 21 | int *v = getValue(3.14); 22 | printf("value = %d\n", *v); 23 | g(); 24 | printf("value = %d\n", *v); 25 | 26 | } 27 | -------------------------------------------------------------------------------- /lectures/sort_and_search.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int max_int(int *arr, int n){ 6 | int max = 0; 7 | for(int i=1; i arr[max]) 9 | max = i; 10 | } 11 | return max; 12 | } 13 | 14 | int comparator(const void *a, const void *b){ 15 | return *((int*)a) - *((int*)b); // (!) 16 | } 17 | 18 | int cmp_strs(const void *a, const void *b){ 19 | char** str1 = (char**)a; 20 | char** str2 = (char**)b; 21 | // printf("%s, %s\n", *str1, *str2); 22 | return strcmp(*str1, *str2); 23 | } 24 | 25 | int cmp_strs_search(const void *a, const void *b){ 26 | char* str1 = (char*)a; 27 | char** str2 = (char**)b; 28 | printf("%s, %s\n", str1, *str2); 29 | return strcmp(str1, *str2); 30 | } 31 | 32 | int universal_max(void *arr, int n, int size, int cmp(const void *, const void *)){ 33 | int max = 0; 34 | for(int i=1; i 2 | class StackEx: public std::exception{ 3 | public: 4 | 5 | const char* what(){ 6 | return "Stack exeption!!"; 7 | } 8 | 9 | }; 10 | 11 | class StackEmptyEx: public StackEx{ 12 | public: 13 | const char* what(){ 14 | return "Stack empty exeption!!"; 15 | } 16 | }; 17 | using std::cout; using std::endl; 18 | 19 | class Stack{ 20 | int *arr; 21 | int n; 22 | int capacity; 23 | 24 | public: 25 | Stack(int c){ 26 | std::cout<<"Stack"<name): %c \n", p3->name); 41 | 42 | printf("LEN: [%d]", sizeof(struct Point)); 43 | 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /lectures/structs/ex2.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define SIZE 10 6 | 7 | struct Point3D { 8 | 9 | char name; 10 | int x; 11 | int y; 12 | 13 | }; 14 | 15 | struct Graph { 16 | 17 | char* title; 18 | struct Point3D* pts; 19 | 20 | }; 21 | 22 | typedef struct Point3D Point3D; 23 | typedef struct Graph Graph; 24 | 25 | int main() { 26 | 27 | // размер структуры 28 | printf("Struct GRAPH holds %ld bytes\n", sizeof(Graph)); 29 | 30 | Graph g; 31 | 32 | // выделение памяти и инициализация 33 | printf("Struct GRAPH holds %p in [pts] field BEFORE alloc\n", g.title); 34 | 35 | g.title = (char*)calloc(100, sizeof(char)); 36 | g.pts = (Point3D*)calloc(SIZE, sizeof(Point3D)); 37 | 38 | // заполнение поля title 39 | strncpy(g.title, "Dependence of the number of platypuses on the volume of quacking in the spring", 100); 40 | 41 | printf("Struct GRAPH holds [%s] in [pts] field\n", g.title); 42 | 43 | // заполнение массива pts 44 | for(int i=0; i 2 | #include 3 | #include 4 | 5 | // базовая цель -- разный тип доступа к данным, хорошо для машинно-независимого кода 6 | union Int { 7 | int digit; 8 | char bin[sizeof(int)]; 9 | double val; 10 | }; 11 | 12 | typedef union Int Int; 13 | 14 | int main() { 15 | 16 | Int a; 17 | a.digit = 4000; 18 | a.val = 20; 19 | 20 | printf("Union size: [%ld]\n", sizeof(Int)); 21 | printf("Double: [%f]\n", a.val); 22 | printf("Digit: [%d], Binary: [%d, %d, %d, %d]\n", a.digit, a.bin[0], a.bin[5], a.bin[6], a.bin[7]); 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /lectures/structs/ex4.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int my_strlen(char* str) { 6 | 7 | int i = 0; 8 | while(str[i] != '\0') 9 | i++; 10 | return i; 11 | } 12 | 13 | // хотим изменить переменную 14 | void plus10(int* a) { 15 | *a += 10; 16 | } 17 | 18 | void replace_ones(char** text) { 19 | 20 | char* s = *text; 21 | int i = 0; 22 | while(s[i] != '\0') { 23 | if(s[i] == '1') 24 | s[i] = '9'; 25 | i++; 26 | } 27 | } 28 | 29 | char* gen_name() { 30 | char*name = "Moisei"; 31 | 32 | // some work 33 | return name; 34 | } 35 | 36 | char* gen_animal() { 37 | char* s = (char*)calloc(20, sizeof(char)); 38 | strncpy(s, "Bear", 20); 39 | return s; 40 | } 41 | 42 | int main() { 43 | 44 | char* s = (char*)calloc(20, sizeof(char)); 45 | strncpy(s, "Ya11hoo111", 20); 46 | printf("LEN: %d\n", my_strlen(s)); 47 | 48 | // изм. аргумента 49 | int b = 40; 50 | plus10(&b); 51 | printf("B val: %d\n", b); 52 | 53 | // изм. строки 54 | printf("NATIVE: [%s]\n", s); 55 | replace_ones(&s); 56 | printf("REPLACED: [%s]\n", s); 57 | 58 | //char* s2 = "ta111pok"; 59 | //replace_ones(&s2); 60 | 61 | // изм. разных строк 62 | char* name = gen_name(); 63 | char* animal = gen_animal(); 64 | 65 | printf("NAME: [%s]\n", name); 66 | printf("ANIMAL: [%s]\n", animal); 67 | //name[0] = 'M'; 68 | animal[0] = 'M'; 69 | printf("ANIMAL: [%s]\n", animal); 70 | 71 | return 0; 72 | } 73 | -------------------------------------------------------------------------------- /lectures/structs/point.h: -------------------------------------------------------------------------------- 1 | struct Point3D { 2 | 3 | char name; 4 | int x; 5 | int y; 6 | 7 | }; 8 | 9 | //кл.сл. тип данных alias 10 | typedef struct Point3D Point3D; 11 | 12 | -------------------------------------------------------------------------------- /lectures/textReading.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #define MEM_STEP 5 5 | // size == 5 6 | // (n < size-2) 7 | // (2 < 3 8 | // |0|1|2|3|4| 9 | // |a|b|c| | | 10 | 11 | struct Sentence{ 12 | char *str; 13 | int size; // != strlen(str) 14 | // ??? 15 | }; 16 | struct Text{ 17 | struct Sentence **sents; 18 | int n; 19 | int size; 20 | }; 21 | 22 | struct Sentence* readSentence(); 23 | 24 | struct Text readText(){ // (!) возвращаем не указатель (!) 25 | int size = MEM_STEP; 26 | struct Sentence** text= malloc(size*sizeof(struct Sentence*)); 27 | int n=0; 28 | struct Sentence* temp; 29 | int nlcount = 0; 30 | do{ 31 | temp = readSentence(); 32 | if(temp->str[0] == '\n') 33 | nlcount++; 34 | // memory leack 35 | else{ 36 | nlcount = 0; 37 | text[n] = temp; 38 | n++; 39 | // puts(temp->str); 40 | } 41 | }while(nlcount<2); 42 | struct Text txt; 43 | txt.size = size; 44 | txt.sents = text; 45 | txt.n = n; 46 | return txt; 47 | } 48 | 49 | struct Sentence* readSentence(){ 50 | int size = MEM_STEP; 51 | char *buf = malloc(size*sizeof(char)); 52 | int n=0; 53 | char temp; 54 | do{ 55 | if(n >= size-2){ 56 | char *t = realloc(buf, size+MEM_STEP); 57 | if(!t){ /* ERROR */} 58 | size+=MEM_STEP; 59 | buf = t; 60 | // printf("new size = %d\n",size); 61 | } 62 | temp = getchar(); 63 | buf[n]= temp; 64 | n++; 65 | }while(temp!='\n' && temp!='.' && temp!='!'); 66 | buf[n]= '\0'; 67 | struct Sentence *sentence = malloc(sizeof(struct Sentence)); 68 | sentence->str = buf; //(*sentence).str = buf; 69 | sentence->size = size; 70 | return sentence; 71 | } 72 | 73 | void sentProc(struct Sentence* sent, int k, int m){ 74 | // sent->str === char* == string 75 | int len = strlen(sent->str); 76 | char *cur_str = sent->str; 77 | // 78 | memmove(cur_str+k, cur_str+k+m, len-m-k+1); 79 | } 80 | 81 | int main(){ 82 | struct Text text = readText(); 83 | sentProc(text.sents[0], 2, 5); 84 | for(int i=0; istr); 87 | } 88 | // Распечатать текст на экран 89 | //1: текст == массив указателей на предл. 90 | //2: каждое предложение == строка 91 | //3: печатать строку мы точно умеем 92 | return 0; 93 | } 94 | -------------------------------------------------------------------------------- /lectures/word_counter.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int main(int argc, char **argv) { 5 | FILE *file = fopen("t.txt","r"); 6 | 7 | if(NULL == file) 8 | return 0; 9 | 10 | int prev = ' '; 11 | int cur; 12 | int wcount = 0; 13 | do { 14 | cur = fgetc (file); 15 | if(cur == EOF) 16 | break; 17 | printf("%c[%d]\n",cur,cur); 18 | if (isspace(cur)) 19 | if(!isspace(prev)){ 20 | wcount++; 21 | } 22 | prev = cur; 23 | } while (cur != EOF); 24 | fclose (file); 25 | if(!isspace(prev)) 26 | wcount++; 27 | printf ("The file contains %d words\n",wcount); 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /libpng/Makefile: -------------------------------------------------------------------------------- 1 | all: 2 | gcc main.c -lpng 3 | -------------------------------------------------------------------------------- /libpng/README.md: -------------------------------------------------------------------------------- 1 | # libpng 2 | libpng - это библиотека для работы с растровой графикой в формате PNG. Так как формат PNG использует сжатие, работа с этим форматом вручную может оказаться более сложной, чем, допустим, с форматом BMP. Для того, что бы облегчить себе жизнь, предлагается использовать библиотеку libpng. 3 | 4 | **Обратите особое внимание на подход к обработке ошибок и исключительных ситуаций!** 5 | 6 | ## Установка 7 | Установить библиотеку можно следующей командой 8 | ``` 9 | sudo apt-get install libpng16-dev 10 | ``` 11 | 12 | ## Сборка 13 | При сборке программы необходимо явно указать линковщику на использование этой библиотеки. Для этого используется флаг `-lpng` 14 | Например: 15 | ``` 16 | gcc my-png-editor.c -lpng 17 | ``` 18 | 19 | ## Примеры и ссылки 20 | - Информация по libpng и самому формату: http://www.libpng.org/ 21 | - В текущей директории содержится простой пример использования библиотеки libpng 22 | - Более полный пример работы с библиотекой: https://github.com/glennrp/libpng/blob/libpng16/example.c 23 | -------------------------------------------------------------------------------- /libpng/main.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | #define PNG_DEBUG 3 8 | #include 9 | 10 | struct Png{ 11 | int width, height; 12 | png_byte color_type; 13 | png_byte bit_depth; 14 | 15 | png_structp png_ptr; 16 | png_infop info_ptr; 17 | int number_of_passes; 18 | png_bytep *row_pointers; 19 | }; 20 | 21 | 22 | void read_png_file(char *file_name, struct Png *image) { 23 | int x,y; 24 | char header[8]; // 8 is the maximum size that can be checked 25 | 26 | /* open file and test for it being a png */ 27 | FILE *fp = fopen(file_name, "rb"); 28 | if (!fp){ 29 | // Some error handling: file could not be opened 30 | } 31 | 32 | fread(header, 1, 8, fp); 33 | if (png_sig_cmp(header, 0, 8)){ 34 | // Some error handling: file is not recognized as a PNG 35 | } 36 | 37 | /* initialize stuff */ 38 | image->png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); 39 | 40 | if (!image->png_ptr){ 41 | // Some error handling: png_create_read_struct failed 42 | } 43 | 44 | image->info_ptr = png_create_info_struct(image->png_ptr); 45 | if (!image->info_ptr){ 46 | // Some error handling: png_create_info_struct failed 47 | } 48 | 49 | if (setjmp(png_jmpbuf(image->png_ptr))){ 50 | // Some error handling: error during init_io 51 | } 52 | 53 | png_init_io(image->png_ptr, fp); 54 | png_set_sig_bytes(image->png_ptr, 8); 55 | 56 | png_read_info(image->png_ptr, image->info_ptr); 57 | 58 | image->width = png_get_image_width(image->png_ptr, image->info_ptr); 59 | image->height = png_get_image_height(image->png_ptr, image->info_ptr); 60 | image->color_type = png_get_color_type(image->png_ptr, image->info_ptr); 61 | image->bit_depth = png_get_bit_depth(image->png_ptr, image->info_ptr); 62 | 63 | image->number_of_passes = png_set_interlace_handling(image->png_ptr); 64 | png_read_update_info(image->png_ptr, image->info_ptr); 65 | 66 | /* read file */ 67 | if (setjmp(png_jmpbuf(image->png_ptr))){ 68 | // Some error handling: error during read_image 69 | } 70 | 71 | image->row_pointers = (png_bytep *) malloc(sizeof(png_bytep) * image->height); 72 | for (y = 0; y < image->height; y++) 73 | image->row_pointers[y] = (png_byte *) malloc(png_get_rowbytes(image->png_ptr, image->info_ptr)); 74 | 75 | png_read_image(image->png_ptr, image->row_pointers); 76 | 77 | fclose(fp); 78 | } 79 | 80 | 81 | void write_png_file(char *file_name, struct Png *image) { 82 | int x,y; 83 | /* create file */ 84 | FILE *fp = fopen(file_name, "wb"); 85 | if (!fp){ 86 | // Some error handling: file could not be opened 87 | } 88 | 89 | /* initialize stuff */ 90 | image->png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL); 91 | 92 | if (!image->png_ptr){ 93 | // Some error handling: png_create_write_struct failed 94 | } 95 | 96 | image->info_ptr = png_create_info_struct(image->png_ptr); 97 | if (!image->info_ptr){ 98 | // Some error handling: png_create_info_struct failed 99 | } 100 | 101 | if (setjmp(png_jmpbuf(image->png_ptr))){ 102 | // Some error handling: error during init_io 103 | } 104 | 105 | png_init_io(image->png_ptr, fp); 106 | 107 | 108 | /* write header */ 109 | if (setjmp(png_jmpbuf(image->png_ptr))){ 110 | // Some error handling: error during writing header 111 | } 112 | 113 | png_set_IHDR(image->png_ptr, image->info_ptr, image->width, image->height, 114 | image->bit_depth, image->color_type, PNG_INTERLACE_NONE, 115 | PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); 116 | 117 | png_write_info(image->png_ptr, image->info_ptr); 118 | 119 | 120 | /* write bytes */ 121 | if (setjmp(png_jmpbuf(image->png_ptr))){ 122 | // Some error handling: error during writing bytes 123 | } 124 | 125 | png_write_image(image->png_ptr, image->row_pointers); 126 | 127 | 128 | /* end write */ 129 | if (setjmp(png_jmpbuf(image->png_ptr))){ 130 | // Some error handling: error during end of write 131 | } 132 | 133 | png_write_end(image->png_ptr, NULL); 134 | 135 | /* cleanup heap allocation */ 136 | for (y = 0; y < image->height; y++) 137 | free(image->row_pointers[y]); 138 | free(image->row_pointers); 139 | 140 | fclose(fp); 141 | } 142 | 143 | 144 | void process_file(struct Png *image) { 145 | int x,y; 146 | if (png_get_color_type(image->png_ptr, image->info_ptr) == PNG_COLOR_TYPE_RGB){ 147 | // Some error handling: input file is PNG_COLOR_TYPE_RGB but must be PNG_COLOR_TYPE_RGBA 148 | } 149 | 150 | if (png_get_color_type(image->png_ptr, image->info_ptr) != PNG_COLOR_TYPE_RGBA){ 151 | // Some error handling: color_type of input file must be PNG_COLOR_TYPE_RGBA 152 | } 153 | 154 | for (y = 0; y < image->height; y++) { 155 | png_byte *row = image->row_pointers[y]; 156 | for (x = 0; x < image->width; x++) { 157 | png_byte *ptr = &(row[x * 4]); 158 | printf("Pixel at position [ %d - %d ] has RGBA values: %d - %d - %d - %d\n", 159 | x, y, ptr[0], ptr[1], ptr[2], ptr[3]); 160 | 161 | /* set red value to 0 and green value to the blue one */ 162 | ptr[0] = 0; 163 | ptr[1] = ptr[2]; 164 | } 165 | } 166 | } 167 | 168 | 169 | int main(int argc, char **argv) { 170 | if (argc != 3){ 171 | fprintf(stderr,"Usage: program_name \n"); 172 | return 0; 173 | } 174 | 175 | struct Png image; 176 | read_png_file(argv[1], &image); 177 | process_file(&image); 178 | write_png_file(argv[2], &image); 179 | 180 | return 0; 181 | } 182 | -------------------------------------------------------------------------------- /libpng/res.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/moevm/pr1-examples/f086fb4ac606b517909a2c4bae0c692144bca833/libpng/res.png -------------------------------------------------------------------------------- /libpng/test.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/moevm/pr1-examples/f086fb4ac606b517909a2c4bae0c692144bca833/libpng/test.png -------------------------------------------------------------------------------- /videos/read_text.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | typedef struct Sentence{ 6 | char *s; 7 | int size; 8 | } Sentence; 9 | 10 | typedef struct Text{ 11 | struct Sentence *sentences; 12 | int size; 13 | int len; 14 | } Text; 15 | 16 | Text initText(){ 17 | Text text; 18 | text.size = 5; 19 | text.len = 0; 20 | text.sentences = malloc(text.size * sizeof(Sentence)); 21 | return text; 22 | } 23 | 24 | void addSentence(Text *text, Sentence sentence){ 25 | if(text->len == text->size){ 26 | text->size+=10; 27 | text->sentences = realloc(text->sentences, text->size * sizeof(Sentence)); //!!!! 28 | } 29 | text->sentences[text->len++] = sentence; 30 | } 31 | 32 | Sentence readSentence(){ 33 | Sentence sentence; 34 | sentence.size = 10; 35 | sentence.s = calloc(sentence.size, sizeof(char)); 36 | int i=0; 37 | int c; 38 | do{ 39 | c = getchar(); 40 | if(c == ' ' && i == 0){ 41 | continue; 42 | } 43 | sentence.s[i++] = c; 44 | if(i==sentence.size){ 45 | sentence.size+=10; 46 | sentence.s = realloc(sentence.s, sentence.size * sizeof(char)); // !!! 47 | } 48 | } while (!strchr(".?!\n", c)); 49 | sentence.s[i] = '\0'; 50 | return sentence; 51 | } 52 | 53 | void freeText(Text *text){ 54 | for(int i=0; ilen; i++){ 55 | free(text->sentences[i].s); 56 | } 57 | free(text->sentences); 58 | } 59 | 60 | int main(){ 61 | 62 | Text text = initText(); 63 | Sentence sentence; 64 | int stop = 0; 65 | do{ 66 | sentence = readSentence(); 67 | if(sentence.s[0] == '\n'){ 68 | free(sentence.s); 69 | stop = 1; 70 | } else { 71 | addSentence(&text, sentence); 72 | } 73 | 74 | } while (!stop); 75 | 76 | for(int i=0; i 2 | #include 3 | #include 4 | 5 | void ins(char *s, char *sub_s, int ins_i){ 6 | memmove(s+ins_i+strlen(sub_s), s+ins_i, strlen(s)-ins_i+1); 7 | memcpy(s+ins_i, sub_s, strlen(sub_s)); 8 | } 9 | 10 | void rem_sub_s(char *s, int rm_i, int rm_len){ 11 | memmove(s+rm_i, s+rm_i+rm_len, strlen(s)-(rm_i+rm_len)+1); 12 | } 13 | 14 | int main(){ 15 | int s_size=20; 16 | char *s = malloc(s_size*sizeof(char)); 17 | char sub_s[]="666"; 18 | strcpy(s, "abcdefg"); 19 | if(strlen(s)+ strlen(sub_s) >= s_size){ 20 | s_size = strlen(s) + strlen(sub_s) + 1; 21 | s = realloc(s, s_size); 22 | } 23 | ins(s, sub_s, 2); 24 | puts(s); 25 | rem_sub_s(s, 2, 3); 26 | puts(s); 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /vulnerabilities/README.md: -------------------------------------------------------------------------------- 1 | ## stack_variables_modification.c 2 | Пример модификации локальный переменных функции 3 | 4 | Демонстрирует опасность бесконтрольной работы с памятью. (в частности, функций копирования `strcpy` и `gets`) 5 | 6 | gcc (в зависимости от платформы) может включать код для защиты от повреждения стека. Это можно отключить с помощью флага `-fno-stack-protector` 7 | 8 | ## return_address_modification.c 9 | Пример модификации адреса возврата и передачи тем самым управления коду, который не должен был выполниться. 10 | 11 | Также требуется сборка с флагом `-fno-stack-protector` для отключения защиты стека и с флагом `-m32` для сборки под 32 разрядную систему (x64 ассемблер гораздо сложнее для понимания). 12 | 13 | Адрес функции doAnything может отличаться от указанного в коде при сборке на вашей машине. Его можно узнать с помощью утилиты `nm` передав ей собранный исполняемый файл. В ее выводе можно найти строчку подобную `08048466 T doAnything` их которой можно узнать адрес функции `doAnything`. Не забудьте про обратный порядок байт. 14 | -------------------------------------------------------------------------------- /vulnerabilities/return_address_modification.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void iAmNotChatterbox(char *key) 5 | { 6 | printf("I will not tell you anything!!!\n"); 7 | char buf[8]; 8 | strcpy(buf,key); //gets() - the same vulnerability 9 | } 10 | 11 | void doAnything() 12 | { 13 | printf("I can do anything for you!!\n"); 14 | } 15 | 16 | int main() 17 | { 18 | char s[32]; 19 | int i; 20 | for(i=0;i<20;i++) 21 | s[i] = 'A'; 22 | 23 | s[i++] = 0x66; 24 | s[i++] = 0x84; 25 | s[i++] = 0x04; 26 | s[i++] = 0x08; 27 | s[i] = 0x00; 28 | iAmNotChatterbox(s); 29 | printf("bye!\n"); 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /vulnerabilities/stack_variables_modification.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int youNeverForceMePrintYes(char *key) 5 | { 6 | int ret = 123; 7 | int verySecretKey = 0; 8 | char buf[8]; 9 | 10 | printf("key = %x\n",verySecretKey); 11 | 12 | strcpy(buf,key); //gets() - the same vulnerability 13 | 14 | printf("key = %x\n",verySecretKey); 15 | 16 | if(verySecretKey == 0x41424344) 17 | printf("Wow! YES!\n"); 18 | else 19 | printf("I say NOOO!\n"); 20 | 21 | return ret; 22 | } 23 | 24 | int main() 25 | { 26 | char s[16] = "12345678DCBA"; 27 | printf("res = %d\n", youNeverForceMePrintYes(s)); 28 | return 0; 29 | } 30 | --------------------------------------------------------------------------------