file
stringlengths
18
26
data
stringlengths
2
1.05M
the_stack_data/98575386.c
struct weak; struct s0 {}; struct s1 { struct s0 a; struct weak* w; }; struct s2 { struct s1 a; struct weak* w; }; struct s3 { struct s1 a; struct s2 b; struct weak* w; }; struct weak { struct s1* a; struct s2* b; struct s3* c; struct weak* w; }; int main() { static struct s1 s1; static struct s2 s2; static struct s3 s3; static struct weak w; return 0; }
the_stack_data/14200065.c
/* { dg-do compile } */ /* { dg-options "-O2 -fno-inline" } */ int f(int *a) { int __attribute__((nonnull(1))) g(int *b) { int **c = &a; if (b) return *a + **c; return *b; } if (a) return g(a); return 1; }
the_stack_data/136674.c
#include <stdbool.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #define MAX_BUF 512 #define CATF "CATALOG.txt" FILE *catalog_f; char name[MAX_BUF][MAX_BUF]; char author[MAX_BUF][MAX_BUF]; char publisher[MAX_BUF][MAX_BUF]; int numBooks = 0; void consumeLine() { while(getchar() != '\n') {} } int menu() { printf("\n"); printf("Card Catalog:\n"); printf("\n"); printf("1: Enter\n"); printf("2: Search by Author\n"); printf("3: Search by Title\n"); printf("4: Quit\n"); printf("5: Save to Disk"); printf("\n"); printf(":"); int code; scanf("%d", &code); consumeLine(); printf("\n"); if (!(1 <= code && code <= 5)) { return 0; } return code; } int writeCatFile() { if ((catalog_f = fopen(CATF, "w")) == NULL) { return 1; } for(int i = 0; i < numBooks; i++) { fputs(name[i], catalog_f); // fputc('\n', catalog_f); fputs(author[i], catalog_f); // fputc('\n', catalog_f); fputs(publisher[i], catalog_f); // fputc('\n', catalog_f); fputc('\n', catalog_f); } fclose(catalog_f); return 0; } int readCatFile() { if(access(CATF, F_OK) != 0) { printf("Unable to access Catalog file.\n"); return 1; } else { if ((catalog_f = fopen(CATF, "r")) == NULL) { return 1; } } int lines = 0; // Count lines while (EOF != (fscanf(catalog_f, "%*[^\n]"), fscanf(catalog_f, "%*c"))) { lines++; } // And reset rewind(catalog_f); if(lines % 4) { printf("Malformed Catalog file? (%d lines)", lines); return 1; } int books = lines / 4; for(int i = 0; i < books; i++) { fgets(name[i], MAX_BUF, catalog_f); fgets(author[i], MAX_BUF, catalog_f); fgets(publisher[i], MAX_BUF, catalog_f); fscanf(catalog_f, "%*c"); // Swallow the empty line } numBooks = books; printf("Read %d books into memory.\n", numBooks); fclose(catalog_f); return 0; } void mEnter() { int nlen, alen, plen; printf("Enter blank name to end.\n"); while(true) { printf("Name: "); fgets(name[numBooks], MAX_BUF, stdin); // If name is blank ("\n\0") if(!(name[numBooks][1])) { break; } printf("Author: "); fgets(author[numBooks], MAX_BUF, stdin); printf("Publisher: "); fgets(publisher[numBooks], MAX_BUF, stdin); numBooks++; } } void menuLogic() { while(true) { int opt = menu(); switch(opt) { case 0: printf("Wrong Option.\n"); break; case 1: mEnter(); break; case 2: printf("NOOP.\n"); break; case 3: printf("NOOP.\n"); break; case 4: return; case 5: if(writeCatFile() == 0) { printf("Wrote to Catalog file.\n"); } else { printf("Failed to write to Catalog file!\n"); } break; } } } int main(int argc, char *argv[]) { // if((name = (char**) malloc(MAX_BUF * MAX_BUF * sizeof(char))) == NULL) { // printf("Unable to allocate memory for 'name[][]'\n"); // } else if((author = (char**) malloc(MAX_BUF * MAX_BUF * sizeof(char))) == NULL) { // printf("Unable to allocate memory for 'author[][]'\n"); // } else if((publisher = (char**) malloc(MAX_BUF * MAX_BUF * sizeof(char))) == NULL) { // printf("Unable to allocate memory for 'publisher[][]'\n"); // } else { // printf("Allocation rules!\n"); // } if(readCatFile() != 0) { printf("Unable to read catalog file into memory!\n"); } menuLogic(); if (catalog_f != NULL) { fclose(catalog_f); } }
the_stack_data/19483.c
#include <stdio.h> #define FALSE 0 #define TRUE !FALSE #define bool int #define MULTIPLE_TO_FIND 1000 int findMultipleSum_efficient(int, int); int findMultipleDupes_efficient(int, int, int, int); int main(int argc, char*argv) { printf("Searching for sum of multiples of 3 and 5 below %d\n", MULTIPLE_TO_FIND); int sum3 = findMultipleSum_efficient(3, MULTIPLE_TO_FIND); int sum5 = findMultipleDupes_efficient(3, 5, MULTIPLE_TO_FIND, findMultipleSum_efficient(5, MULTIPLE_TO_FIND)); int totalSum = sum3 + sum5; printf("Sum of 3 = %d\nSum of 5 = %d\nSum of both = %d\n", sum3, sum5, totalSum); return 1; } int findMultipleSum_efficient(int rootMultiple, int maxValue) { //changes 1000/5 to 999/5 or 30/3 to 29/3 to keep the multiple BELOW the maxValue passed in int largestIndex; if(maxValue % rootMultiple == 0) largestIndex = (maxValue - 1) / rootMultiple; else largestIndex = maxValue / rootMultiple; int largestValue = largestIndex * rootMultiple; int smallestValue = rootMultiple; //Compute the totalSum by using math instead of bruteforcing int totalSum = 0; if(largestIndex % 2 != 0)//It is odd //If it is odd we have to add the middle modulus (aka the middle) value to the result { totalSum = largestValue + smallestValue; totalSum = totalSum * (largestIndex / 2); totalSum = ((largestIndex / 2) + 1) * rootMultiple + totalSum; } else //If it is even we do not have to add the middle value to the result { totalSum = largestValue + smallestValue; totalSum = totalSum * (largestIndex / 2); } return totalSum; } int findMultipleDupes_efficient(int rootMultipleA, int rootMultipleB, int maxValue, int totalSumOfMultipleB) { //This value is duplicated totalSumOfMultipleB / (rootMultipleA * rootMultipleB) times int dupedValue = rootMultipleA * rootMultipleB; int dupedSum = findMultipleSum_efficient(dupedValue, maxValue); printf("Duplicated Multiple to find = %d : Duplicated Total Sum = %d\n", dupedValue, dupedSum); return totalSumOfMultipleB - dupedSum; }
the_stack_data/111132.c
#include<stdio.h> #include<unistd.h> int main(int argc, char * argv[]) { printf("Executе program: %s\n", argv[0]); printf("Process Identification Number (pid): %i\n", getpid()); printf("Parent pid = %i\n", getppid()); return 0; }
the_stack_data/103265156.c
#include <stdbool.h> bool ffiTrue() { return true; }
the_stack_data/28262039.c
#include <stdlib.h> long randlong() { long ret = rand(); ret |= rand() << sizeof(int); return abs(ret); } void swap_ll(long long *first, long long *second) { long long tmp = *first; *first = *second; *second = tmp; } int partition(long long *arr, int elem_cnt) { int pivot_idx = randlong() % elem_cnt; long long pivot = arr[pivot_idx]; long long *l = &arr[0]; long long *r = &arr[elem_cnt - 1]; while (1) { while (*l < pivot && l < r) { ++l; } while (*r >= pivot && l < r) { --r; } swap_ll(l, r); if (l >= r) { break; } } return (int) (l - arr); } int main() { return 0; }
the_stack_data/36075679.c
/* ******************************************************************************* * Copyright (c) 2020-2021, STMicroelectronics * All rights reserved. * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ******************************************************************************* */ /* * Automatically generated from STM32L072R(B-Z)Tx.xml, STM32L073R(B-Z)Tx.xml * STM32L083R(B-Z)Tx.xml * CubeMX DB release 6.0.20 */ #if defined(ARDUINO_PX_HER0) #include "Arduino.h" #include "PeripheralPins.h" /* ===== * Notes: * - The pins mentioned Px_y_ALTz are alternative possibilities which use other * HW peripheral instances. You can use them the same way as any other "normal" * pin (i.e. analogWrite(PA7_ALT1, 128);). * * - Commented lines are alternative possibilities which are not used per default. * If you change them, you will have to know what you do * ===== */ //*** ADC *** #ifdef HAL_ADC_MODULE_ENABLED WEAK const PinMap PinMap_ADC[] = { // {PA_0, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 0, 0)}, // ADC_IN0 // {PA_1, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 1, 0)}, // ADC_IN1 // {PA_2, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 2, 0)}, // ADC_IN2 // {PA_3, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 3, 0)}, // ADC_IN3 // {PA_4, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 4, 0)}, // ADC_IN4 // {PA_5, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 5, 0)}, // ADC_IN5 // {PA_6, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 6, 0)}, // ADC_IN6 {PA_7, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 7, 0)}, // ADC_IN7 {PB_0, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 8, 0)}, // ADC_IN8 {PB_1, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 9, 0)}, // ADC_IN9 // {PC_0, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 10, 0)}, // ADC_IN10 // {PC_1, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 11, 0)}, // ADC_IN11 // {PC_2, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 12, 0)}, // ADC_IN12 // {PC_3, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 13, 0)}, // ADC_IN13 {PC_4, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 14, 0)}, // ADC_IN14 {PC_5, ADC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 15, 0)}, // ADC_IN15 {NC, NP, 0} }; #endif //*** DAC *** #ifdef HAL_DAC_MODULE_ENABLED WEAK const PinMap PinMap_DAC[] = { {PA_4, DAC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 1, 0)}, // DAC_OUT1 // {PA_5, DAC1, STM_PIN_DATA_EXT(STM_MODE_ANALOG, GPIO_NOPULL, 0, 2, 0)}, // DAC_OUT2 {NC, NP, 0} }; #endif //*** I2C *** #ifdef HAL_I2C_MODULE_ENABLED WEAK const PinMap PinMap_I2C_SDA[] = { // {PA_10, I2C1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF6_I2C1)}, // {PB_4, I2C3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF7_I2C3)}, // {PB_7, I2C1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF1_I2C1)}, {PB_9, I2C1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, // {PB_11, I2C2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF6_I2C2)}, // {PB_14, I2C2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF5_I2C2)}, // {PC_1, I2C3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF7_I2C3)}, // {PC_9, I2C3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF7_I2C3)}, {NC, NP, 0} }; #endif #ifdef HAL_I2C_MODULE_ENABLED WEAK const PinMap PinMap_I2C_SCL[] = { // {PA_8, I2C3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF7_I2C3)}, // {PA_9, I2C1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF6_I2C1)}, // {PB_6, I2C1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF1_I2C1)}, {PB_8, I2C1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, // {PB_10, I2C2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF6_I2C2)}, // {PB_13, I2C2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF5_I2C2)}, // {PC_0, I2C3, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF7_I2C3)}, {NC, NP, 0} }; #endif //*** TIM *** #ifdef HAL_TIM_MODULE_ENABLED WEAK const PinMap PinMap_TIM[] = { {PA_0, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2, 1, 0)}, // TIM2_CH1 {PA_1, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2, 2, 0)}, // TIM2_CH2 // {PA_2, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2, 3, 0)}, // TIM2_CH3 // {PA_2_ALT1, TIM21, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_TIM21, 1, 0)}, // TIM21_CH1 // {PA_3, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2, 4, 0)}, // TIM2_CH4 // {PA_3_ALT1, TIM21, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_TIM21, 2, 0)}, // TIM21_CH2 {PA_5, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_TIM2, 1, 0)}, // TIM2_CH1 {PA_6, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1 {PA_6_ALT1, TIM22, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_TIM22, 1, 0)}, // TIM22_CH1 // {PA_7, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 // {PA_7_ALT1, TIM22, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_TIM22, 2, 0)}, // TIM22_CH2 // {PA_15, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_TIM2, 1, 0)}, // TIM2_CH1 // {PB_0, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 3, 0)}, // TIM3_CH3 // {PB_1, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 4, 0)}, // TIM3_CH4 // {PB_3, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2, 2, 0)}, // TIM2_CH2 // {PB_4, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1 // {PB_4_ALT1, TIM22, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_TIM22, 1, 0)}, // TIM22_CH1 // {PB_5, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_TIM3, 2, 0)}, // TIM3_CH2 // {PB_5_ALT1, TIM22, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_TIM22, 2, 0)}, // TIM22_CH2 // {PB_10, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2, 3, 0)}, // TIM2_CH3 // {PB_11, TIM2, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2, 4, 0)}, // TIM2_CH4 // {PB_13, TIM21, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_TIM21, 1, 0)}, // TIM21_CH1 // {PB_14, TIM21, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_TIM21, 2, 0)}, // TIM21_CH2 {PC_6, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 1, 0)}, // TIM3_CH1 {PC_6_ALT1, TIM22, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_TIM22, 1, 0)}, // TIM22_CH1 // {PC_7, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 2, 0)}, // TIM3_CH2 // {PC_7_ALT1, TIM22, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_TIM22, 2, 0)}, // TIM22_CH2 // {PC_8, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 3, 0)}, // TIM3_CH3 // {PC_9, TIM3, STM_PIN_DATA_EXT(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3, 4, 0)}, // TIM3_CH4 {NC, NP, 0} }; #endif //*** UART *** #ifdef HAL_UART_MODULE_ENABLED WEAK const PinMap PinMap_UART_TX[] = { // {PA_0, USART4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_USART4)}, {PA_2, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_LPUART1)}, {PA_2_ALT1, USART2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART2)}, {PA_9, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART1)}, // {PA_14, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_LPUART1)}, // {PA_14_ALT1, USART2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART2)}, // {PB_3, USART5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_USART5)}, // {PB_6, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_USART1)}, // {PB_10, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_LPUART1)}, // {PB_11, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_LPUART1)}, // {PC_1, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_LPUART1)}, // {PC_4, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_LPUART1)}, {PC_10, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_LPUART1)}, {PC_10_ALT1, USART4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_USART4)}, // {PC_12, USART5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_USART5)}, {NC, NP, 0} }; #endif #ifdef HAL_UART_MODULE_ENABLED WEAK const PinMap PinMap_UART_RX[] = { // {PA_1, USART4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_USART4)}, {PA_3, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_LPUART1)}, {PA_3_ALT1, USART2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART2)}, {PA_10, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART1)}, // {PA_13, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_LPUART1)}, // {PA_15, USART2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART2)}, // {PB_4, USART5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_USART5)}, // {PB_7, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_USART1)}, // {PB_10, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF7_LPUART1)}, // {PB_11, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_LPUART1)}, // {PC_0, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_LPUART1)}, // {PC_5, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_LPUART1)}, {PC_11, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_LPUART1)}, {PC_11_ALT1, USART4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_USART4)}, // {PD_2, USART5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_USART5)}, {NC, NP, 0} }; #endif #ifdef HAL_UART_MODULE_ENABLED WEAK const PinMap PinMap_UART_RTS[] = { // {PA_1, USART2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART2)}, // {PA_12, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART1)}, // {PA_15, USART4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_USART4)}, // {PB_1, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_LPUART1)}, // {PB_3, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_USART1)}, // {PB_5, USART5, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_USART5)}, // {PB_12, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_LPUART1)}, // {PB_14, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_LPUART1)}, // {PD_2, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_LPUART1)}, {NC, NP, 0} }; #endif #ifdef HAL_UART_MODULE_ENABLED WEAK const PinMap PinMap_UART_CTS[] = { // {PA_0, USART2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART2)}, // {PA_6, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_LPUART1)}, // {PA_11, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART1)}, // {PB_4, USART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_USART1)}, // {PB_7, USART4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_USART4)}, // {PB_13, LPUART1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_LPUART1)}, {NC, NP, 0} }; #endif //*** SPI *** #ifdef HAL_SPI_MODULE_ENABLED WEAK const PinMap PinMap_SPI_MOSI[] = { // {PA_7, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, // {PA_12, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, {PB_5, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, {PB_15, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI2)}, // {PC_3, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_SPI2)}, {NC, NP, 0} }; #endif #ifdef HAL_SPI_MODULE_ENABLED WEAK const PinMap PinMap_SPI_MISO[] = { // {PA_6, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, // {PA_11, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, {PB_4, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, {PB_14, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI2)}, // {PC_2, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_SPI2)}, {NC, NP, 0} }; #endif #ifdef HAL_SPI_MODULE_ENABLED WEAK const PinMap PinMap_SPI_SCLK[] = { // {PA_5, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, {PB_3, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, // {PB_10, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, {PB_13, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI2)}, {NC, NP, 0} }; #endif #ifdef HAL_SPI_MODULE_ENABLED WEAK const PinMap PinMap_SPI_SSEL[] = { // {PA_4, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, // {PA_15, SPI1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, // {PB_9, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, // {PB_12, SPI2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI2)}, {NC, NP, 0} }; #endif //*** No CAN *** //*** No ETHERNET *** //*** No QUADSPI *** //*** USB *** #if defined(HAL_PCD_MODULE_ENABLED) || defined(HAL_HCD_MODULE_ENABLED) WEAK const PinMap PinMap_USB[] = { {PA_11, USB, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, GPIO_AF_NONE)}, // USB_DM {PA_12, USB, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, GPIO_AF_NONE)}, // USB_DP // {PA_13, USB, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_USB)}, // USB_NOE // {PC_9, USB, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_USB)}, // USB_NOE {NC, NP, 0} }; #endif //*** No SD *** #endif /* ARDUINO_PX_HER0 */
the_stack_data/125139351.c
// Copyright (c) 2015 RV-Match Team. All Rights Reserved. int f(int* restrict a, int* restrict b) { *a = 1; *b = 1; return 0; } int main(void) { int a = 5; return f(&a, &a); }
the_stack_data/20101.c
// // dishiyizhang15.c // dishiyizhang // // Created by mingyue on 15/11/3. // Copyright © 2015年 G. All rights reserved. // #include <stdio.h> #include <string.h> #define SIZE 40 #define TARGSIZE 7 #define LIM 5 int main(int argc, const char* argv[]){ char qwords[LIM][TARGSIZE]; char temp[SIZE]; int i = 0; printf("Enter %d words beginning with q: \n",LIM); while (i < LIM && gets(temp)) { if (strncmp(temp, "q", 1)) { printf("%s doesn't begin with q!\n",temp); }else{ strncpy(qwords[i], temp, TARGSIZE - 1); qwords[i][TARGSIZE - 1] = '\0'; i++; } } puts("Here are the words accepted:"); for (i = 0; i < LIM; i++) { puts(qwords[i]); } return 0; }
the_stack_data/486727.c
#include <stdio.h> #include <stdlib.h> int main(int argc, char** argv) { for (int i = 1; i < argc; i++) printf("%s%c", argv[i], i == argc - 1 ? '\n' : ' '); return 0; }
the_stack_data/234518767.c
/*************************************************************************** * FILENAME: draw_wave.c C VERSION * DESCRIPTION: * Called by mpi_wave routines to draw a graph of results * AUTHOR: Blaise Barney * LAST REVISED: 01/26/09 ***************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #define HEIGHT 500 #define WIDTH 1000 typedef struct { Window window; XSizeHints hints; XColor backcolor; XColor bordcolor; int bordwidth; } MYWINDOW; char baseword[] = {"draw_wave"}, exitword[] = {"Exit"}, text[10]; /* To call from Fortran: uncomment the routine below with the extra underscore in the name void draw_wave_(double * results) { */ /* To call from C, use the routine below - without the extra underscore */ void draw_wave(double * results) { /* Note extra underscore in draw_wave routine - needed for Fortran */ float scale, point, coloratio = 65535.0 / 255.0; int i,j,k,y, zeroaxis, done, myscreen, points[WIDTH]; MYWINDOW base, quit; Font font,font2; GC itemgc,textgc,pointgc,linegc; XColor red,yellow,blue,green,black,white; XEvent myevent; Colormap cmap; KeySym mykey; Display *mydisp; /* Set rgb values for colors */ red.red= (int) (255 * coloratio); red.green= (int) (0 * coloratio); red.blue = (int) (0 * coloratio); yellow.red= (int) (255 * coloratio); yellow.green= (int) (255 * coloratio); yellow.blue= (int) (0 * coloratio); blue.red= (int) (0 * coloratio); blue.green= (int) (0 * coloratio); blue.blue= (int) (255 * coloratio); green.red= (int) (0 * coloratio); green.green= (int) (255 * coloratio); green.blue= (int) (0 * coloratio); black.red= (int) (0 * coloratio); black.green= (int) (0 * coloratio); black.blue= (int) (0 * coloratio); white.red= (int) (255 * coloratio); white.green= (int) (255 * coloratio); white.blue= (int) (255 * coloratio); mydisp = XOpenDisplay(""); if (!mydisp) { fprintf (stderr, "Hey! Either you don't have X or something's not right.\n"); fprintf (stderr, "Guess I won't be showing the graph. No big deal.\n"); exit(1); } myscreen = DefaultScreen(mydisp); cmap = DefaultColormap (mydisp, myscreen); XAllocColor (mydisp, cmap, &red); XAllocColor (mydisp, cmap, &yellow); XAllocColor (mydisp, cmap, &blue); XAllocColor (mydisp, cmap, &black); XAllocColor (mydisp, cmap, &green); XAllocColor (mydisp, cmap, &white); /* Set up for creating the windows */ /* XCreateSimpleWindow uses defaults for many attributes, */ /* thereby simplifying the programmer's work in many cases. */ /* base window position and size */ base.hints.x = 50; base.hints.y = 50; base.hints.width = WIDTH; base.hints.height = HEIGHT; base.hints.flags = PPosition | PSize; base.bordwidth = 5; /* window Creation */ /* base window */ base.window = XCreateSimpleWindow (mydisp, DefaultRootWindow (mydisp), base.hints.x, base.hints.y, base.hints.width, base.hints.height, base.bordwidth, black.pixel, black.pixel); XSetStandardProperties (mydisp, base.window, baseword, baseword, None, NULL, 0, &base.hints); /* quit window position and size (subwindow of base) */ quit.hints.x = 5; quit.hints.y = 450; quit.hints.width = 70; quit.hints.height = 30; quit.hints.flags = PPosition | PSize; quit.bordwidth = 5; quit.window = XCreateSimpleWindow (mydisp, base.window, quit.hints.x, quit.hints.y, quit.hints.width, quit.hints.height, quit.bordwidth, green.pixel, yellow.pixel); XSetStandardProperties (mydisp, quit.window, exitword, exitword, None, NULL, 0, &quit.hints); /* Load fonts */ /* font = XLoadFont (mydisp, "Rom28"); font2 = XLoadFont (mydisp, "Rom17.500"); */ font = XLoadFont (mydisp, "fixed"); font2 = XLoadFont (mydisp, "fixed"); /* GC creation and initialization */ textgc = XCreateGC (mydisp, base.window, 0,0); XSetFont (mydisp, textgc, font); XSetForeground (mydisp, textgc, white.pixel); linegc = XCreateGC (mydisp, base.window, 0,0); XSetForeground (mydisp, linegc, white.pixel); itemgc = XCreateGC (mydisp, quit.window, 0,0); XSetFont (mydisp, itemgc, font2); XSetForeground (mydisp, itemgc, black.pixel); pointgc = XCreateGC (mydisp, base.window, 0,0); XSetForeground (mydisp, pointgc, green.pixel); /* The program is event driven; the XSelectInput call sets which */ /* kinds of interrupts are desired for each window. */ /* These aren't all used. */ XSelectInput (mydisp, base.window, ButtonPressMask | KeyPressMask | ExposureMask); XSelectInput (mydisp, quit.window, ButtonPressMask | KeyPressMask | ExposureMask); /* window mapping -- this lets windows be displayed */ XMapRaised (mydisp, base.window); XMapSubwindows (mydisp, base.window); /* Scale each data point */ zeroaxis = HEIGHT/2; scale = (float)zeroaxis; for(j=0;j<WIDTH;j++) points[j] = zeroaxis - (int)(results[j] * scale); /* Main event loop -- exits when user clicks on "exit" */ done = 0; while (! done) { XNextEvent (mydisp, &myevent); /* Read next event */ switch (myevent.type) { case Expose: if (myevent.xexpose.count == 0) { if (myevent.xexpose.window == base.window) { XDrawString (mydisp, base.window, textgc, 775, 30, "Wave",4); XDrawLine (mydisp, base.window, linegc, 1,zeroaxis,WIDTH, zeroaxis); for (j=1; j<WIDTH; j++) XDrawPoint (mydisp, base.window, pointgc, j, points[j-1]); } else if (myevent.xexpose.window == quit.window) { XDrawString (mydisp, quit.window, itemgc, 12,20, exitword, strlen(exitword)); } } /* case Expose */ break; case ButtonPress: if (myevent.xbutton.window == quit.window) done = 1; break; case KeyPress: /* i = XLookupString (&myevent, text, 10, &mykey, 0); if (i == 1 && text[0] == 'q') done = 1; */ break; case MappingNotify: /* XRefreshKeyboardMapping (&myevent); */ break; } /* switch (myevent.type) */ } /* while (! done) */ XDestroyWindow (mydisp, base.window); XCloseDisplay (mydisp); }
the_stack_data/129738.c
#include <ncurses.h> #define DELAY 1000 int main(void) { int ch; initscr(); timeout(DELAY); printw("The timeout delay has been set to %d milliseconds.\n",DELAY); addstr("Try to type in your name fast enough:\n"); refresh(); do { ch = getch(); if(ch == '\n') break; } while(ch != ERR); mvaddstr(5,0,"Hope you got it all in!"); refresh(); getch(); endwin(); return 0; }
the_stack_data/21289.c
/*************************************************************************** * Variant Packbits Encoding and Decoding Library * * File : vpackbits.c * Purpose : Use a variant of packbits run length coding to compress and * decompress files. This packbits variant begins each block of * data with the a byte header that is decoded as follows. * * Byte (n) | Meaning * -----------+------------------------------------- * 0 - 127 | Copy the next n + 1 bytes * -128 - -1 | Make -n + 2 copies of the next byte * * Author : Michael Dipperstein * Date : September 7, 2006 * **************************************************************************** * * VPackBits: ANSI C PackBits Style Run Length Encoding/Decoding Routines * Copyright (C) 2006-2007, 2015 by * Michael Dipperstein ([email protected]) * * This file is part of the RLE library. * * The RLE library is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * The RLE library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser * General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ***************************************************************************/ /*************************************************************************** * INCLUDED FILES ***************************************************************************/ #include <stdio.h> #include <limits.h> #include <errno.h> /*************************************************************************** * CONSTANTS ***************************************************************************/ #define MIN_RUN 3 /* minimum run length to encode */ #define MAX_RUN (128 + MIN_RUN - 1) /* maximum run length to encode */ #define MAX_COPY 128 /* maximum characters to copy */ /* maximum that can be read before copy block is written */ #define MAX_READ (MAX_COPY + MIN_RUN - 1) /*************************************************************************** * FUNCTIONS ***************************************************************************/ /*************************************************************************** * Function : VPackBitsEncodeFile * Description: This routine reads an input file and writes out a run * length encoded version of that file. The technique used * is a variation of the packbits technique. * Parameters : inFile - Pointer to the file to encode * outFile - Pointer to the file to write encoded output to * Effects : File is encoded using RLE * Returned : 0 for success, -1 for failure. errno will be set in the * event of a failure. Either way, inFile and outFile will * be left open. ***************************************************************************/ int VPackBitsEncodeFile(FILE *inFile, FILE *outFile) { int currChar; /* current character */ unsigned char charBuf[MAX_READ]; /* buffer of already read characters */ unsigned char count; /* number of characters in a run */ /* validate input and output files */ if ((NULL == inFile) || (NULL == outFile)) { errno = ENOENT; return -1; } /* prime the read loop */ currChar = fgetc(inFile); count = 0; /* read input until there's nothing left */ while (currChar != EOF) { charBuf[count] = (unsigned char)currChar; count++; if (count >= MIN_RUN) { int i; /* check for run charBuf[count - 1] .. charBuf[count - MIN_RUN]*/ for (i = 2; i <= MIN_RUN; i++) { if (currChar != charBuf[count - i]) { /* no run */ i = 0; break; } } if (i != 0) { /* we have a run write out buffer before run*/ int nextChar; if (count > MIN_RUN) { /* block size - 1 followed by contents */ fputc(count - MIN_RUN - 1, outFile); fwrite(charBuf, sizeof(unsigned char), count - MIN_RUN, outFile); } /* determine run length (MIN_RUN so far) */ count = MIN_RUN; while ((nextChar = fgetc(inFile)) == currChar) { count++; if (MAX_RUN == count) { /* run is at max length */ break; } } /* write out encoded run length and run symbol */ fputc((char)((int)(MIN_RUN - 1) - (int)(count)), outFile); fputc(currChar, outFile); if ((nextChar != EOF) && (count != MAX_RUN)) { /* make run breaker start of next buffer */ charBuf[0] = nextChar; count = 1; } else { /* file or max run ends in a run */ count = 0; } } } if (MAX_READ == count) { int i; /* write out buffer */ fputc(MAX_COPY - 1, outFile); fwrite(charBuf, sizeof(unsigned char), MAX_COPY, outFile); /* start a new buffer */ count = MAX_READ - MAX_COPY; /* copy excess to front of buffer */ for (i = 0; i < count; i++) { charBuf[i] = charBuf[MAX_COPY + i]; } } currChar = fgetc(inFile); } /* write out last buffer */ if (0 != count) { if (count <= MAX_COPY) { /* write out entire copy buffer */ fputc(count - 1, outFile); fwrite(charBuf, sizeof(unsigned char), count, outFile); } else { /* we read more than the maximum for a single copy buffer */ fputc(MAX_COPY - 1, outFile); fwrite(charBuf, sizeof(unsigned char), MAX_COPY, outFile); /* write out remainder */ count -= MAX_COPY; fputc(count - 1, outFile); fwrite(&charBuf[MAX_COPY], sizeof(unsigned char), count, outFile); } } return 0; } /*************************************************************************** * Function : VPackBitsDecodeFile * Description: This routine opens a file encoded by a variant of the * packbits run length encoding, and decodes it to an output * file. * Parameters : inFile - Pointer to the file to decode * outFile - Pointer to the file to write decoded output to * Effects : Encoded file is decoded * Returned : 0 for success, -1 for failure. errno will be set in the * event of a failure. Either way, inFile and outFile will * be left open. ***************************************************************************/ int VPackBitsDecodeFile(FILE *inFile, FILE *outFile) { int countChar; /* run/copy count */ int currChar; /* current character */ /* validate input and output files */ if ((NULL == inFile) || (NULL == outFile)) { errno = ENOENT; return -1; } /* decode inFile */ /* read input until there's nothing left */ while ((countChar = fgetc(inFile)) != EOF) { countChar = (char)countChar; /* force sign extension */ if (countChar < 0) { /* we have a run write out 2 - countChar copies */ countChar = (MIN_RUN - 1) - countChar; if (EOF == (currChar = fgetc(inFile))) { fprintf(stderr, "Run block is too short!\n"); countChar = 0; } while (countChar > 0) { fputc(currChar, outFile); countChar--; } } else { /* we have a block of countChar + 1 symbols to copy */ for (countChar++; countChar > 0; countChar--) { if ((currChar = fgetc(inFile)) != EOF) { fputc(currChar, outFile); } else { fprintf(stderr, "Copy block is too short!\n"); break; } } } } return 0; }
the_stack_data/151705146.c
/*------------------------------------------------------------------------- sqrtf.c - Computes square root of a 32-bit float as outlined in [1] Copyright (C) 2001, 2002, Jesus Calvino-Fraga, [email protected] This library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this library; see the file COPYING. If not, write to the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. As a special exception, if you link this library with other files, some of which are compiled with SDCC, to produce an executable, this library does not by itself cause the resulting executable to be covered by the GNU General Public License. This exception does not however invalidate any other reasons why the executable file might be covered by the GNU General Public License. [1] William James Cody and W. M. Waite. _Software manual for the elementary functions_, Englewood Cliffs, N.J.:Prentice-Hall, 1980. Version 1.0 - Initial release kio 2014-11-26 removed keyword FLOAT_FUNC_REENTRANT because functions on the z80 are always rentrant */ #include <math.h> #include <errno.h> float sqrtf(float x) { float f, y; int n; if (x==0.0) return x; else if (x==1.0) return 1.0; else if (x<0.0) { errno=EDOM; return 0.0; } f=frexpf(x, &n); y=0.41731+0.59016*f; /*Educated guess*/ /*For a 24 bit mantisa (float), two iterations are sufficient*/ y+=f/y; y=ldexpf(y, -2) + f/y; /*Faster version of 0.25 * y + f/y*/ if (n&1) { y*=0.7071067812; ++n; } return ldexpf(y, n/2); }
the_stack_data/7950674.c
#include <stdio.h> /* * Programa de testes dos tipos e tamanhos */ void main (void){ int vazio[5]; int vetor[] = { 1, 2, 3 }; //quantidade de elementos printf("%d\n", sizeof(vazio) / 4); printf("%d\n", sizeof(vetor) / 4); }
the_stack_data/22013803.c
/*************************************************************************************************** * Created by JEP on Nov 13, 2016 testing of Linux poll() and related code. KEY Features: * * 1. name to IP address lookup, no need for hard coded IP address. * * 2. Open and correct ussage (on BeagleBone at least) of GPIO bits so poll() will work * * 3. Keyboard input (just basic line input however, no key by key support) * * 4. Network send of events, key board input * * 5. Network receive of whatever we want * * * * To compile: * * gcc -Wall -oprog07 07-multiStreamWithNameLookup.c * * * * NOTE: * * gcc -std=c99 -Wall -oprog04 04-multiStreamTest.c breaks things * * inet_aton() in arpa/inet.h does not get defined * * See /usr/include/features.h for more details * * _SVID_SOURCE, _BSD_SOURCE, and _POSIX_SOURCE set to one might fix * * * * * * NOTES: * * Manual commands GPIO using bash shell * * echo 66 > /sys/class/gpio/export # Enable I/O port 66 (pin 7) * * echo 67 > /sys/class/gpio/export # Enable I/O port 66 (pin 8) * * * * Set the two pin's 'interrupt' state (none, both, rising, falling) * * echo none >/sys/class/gpio/gpio66/edge ; echo none >/sys/class/gpio/gpio67/edge * * echo both >/sys/class/gpio/gpio66/edge ; echo both >/sys/class/gpio/gpio67/edge * * * * echo out >/sys/class/gpio/gpio45/direction # Set for output * * echo in >/sys/class/gpio/gpio45/direction # Set for input * * * * cat /sys/class/gpio/gpio67/value # Shows current state * * * * * ***************************************************************************************************/ #include <stdio.h> // printf(), getline() #include <stdlib.h> // exit() #include <string.h> // memset(), strerror() #include <sys/time.h> #include <time.h> // time(), time_t, strftime() extern int errno; // required for sterror() usage #include <sys/ioctl.h> #include <sys/poll.h> #include <netdb.h> // getaddrinfo(), inet_ntop(), related stuff #include <sys/types.h> // open(), O_RDONLY | O_DIRECT #include <sys/socket.h> #include <arpa/inet.h> // inet_aton() #include <sys/stat.h> // open(), O_RDONLY | O_DIRECT #include <fcntl.h> // open(), O_RDONLY | O_DIRECT #include <unistd.h> // close(), read(), write() #include <errno.h> // strerror() #include <poll.h> // poll(), ?? #include <signal.h> // for Ctrl-C catch, signal(SIGINT, intHandler); #include <stdbool.h> // type bool, true, false #define BUFLEN 512 //Max length of buffer char serverName[500]; char serverIP_Addr[100]; int serverPORT_Num = 3033; /*************************************************************************************************** * Globals. myFD_Ctrl[] and fds[] are parallel arrays. poll() call requires array fds[], to not * * go mad/write garbage code we require myFD_Ctrl[]. During the main loop numActiveFDs is the * * number of entries in the two arrays. fds[X] and myFD_Ctrl[X] MUST always be in sync. * * * * * ***************************************************************************************************/ #define MAX_FDS 20 struct pollfd fds[MAX_FDS]; struct myFD_Ctrl { int handle; char RX_Buf[BUFLEN+1]; char TX_Buf[BUFLEN+1]; // size_t rxLen, txLen; int msgNum; struct sockaddr_in si_other; size_t slen; // Is this really effectivly a constant? size_t recv_len; // for TCP sockets I have to deal with partial data on reads. I will need this if that is an issue for UDP sockets void (*processInput) (int entry, bool timeOut); bool closeRequired; char *name; } myFD_Ctrl[MAX_FDS]; int timeOutMilliSecs; static volatile bool keepGoing; int numActiveFDs = 0; // except when there are no active entries, always points one past last entry int entrySTDIN; // Channel/entry for stdin (keyboard is assumed) int entrySOCKET; // Channel/entry for the socket typedef void (*PROCESS_INPUT) (int entry, bool timeOut); /*************************************************************************************************** * * ***************************************************************************************************/ void intHandler (int dummy) { if (!keepGoing) { printf ("%03d: ERROR: intHandler() called twice, preforming HARD ABORT \n", __LINE__); /* * The program should be constantly running the main program loop, and the first time * we see Ctrl-C it should have seen it and quit. But if a handler is stuck in an endless * loop then the program as a whole will just run forever. In that situation when we get * a second Ctrl-C we abort from within this signal hander. Other wise we can become an un-killable * process thanks to our trapping Ctrl-C. */ int entry; for (entry = 0; entry < numActiveFDs; entry++) { if (myFD_Ctrl[entry].closeRequired) close(myFD_Ctrl[entry].handle); } exit (4); } keepGoing = false; // Tell main loop its time to shutdown return; } /*************************************************************************************************** * Meant to be used in decodeEventsMask() and no where else * * * ***************************************************************************************************/ static void decodeEventsMask_Sub (char **dest, char *str) { while (*str) { *(*dest)++ = *str++; } *(*dest)++ = ','; *(*dest)++ = ' '; *(*dest) = '\0'; } #define EVT_TEST(buf, flags, mask) if (flags & mask) { decodeEventsMask_Sub (buf, #mask); flags = flags & (~mask); } /*************************************************************************************************** * Convert poll() event flag codes into human readable strings. Intended for diagnostics only * * * ***************************************************************************************************/ char *decodeEventsMask (unsigned int flags) { static char msgBuf[900]; char *s; if (flags == 0) { strcpy (msgBuf, "none"); return msgBuf; } s = msgBuf; EVT_TEST (&s, flags, POLLIN); EVT_TEST (&s, flags, POLLPRI); EVT_TEST (&s, flags, POLLOUT); // EVT_TEST (&s, flags, POLLRDHUP); EVT_TEST (&s, flags, POLLERR); EVT_TEST (&s, flags, POLLHUP); EVT_TEST (&s, flags, POLLNVAL); if (flags != 0) { sprintf (s, "unknown bits %04X, ", flags); s = s + strlen (s); } // Strip trailing space & comma *s-- = '\0'; // Silly, but cheaper than an if() *s-- = '\0'; // the trailing space *s-- = '\0'; // the trailing comma return msgBuf; } /*************************************************************************************************** * * ***************************************************************************************************/ void sendMessageToSocket (char *msg, int senderEntryNum) { sprintf (myFD_Ctrl[entrySOCKET].TX_Buf, "=%02d@%s=", myFD_Ctrl[entrySOCKET].msgNum, msg); if (sendto (myFD_Ctrl[entrySOCKET].handle, myFD_Ctrl[entrySOCKET].TX_Buf, strlen(myFD_Ctrl[entrySOCKET].TX_Buf), 0 , (struct sockaddr *) &myFD_Ctrl[entrySOCKET].si_other, myFD_Ctrl[entrySOCKET].slen) == -1) { printf ("%3d: ERROR: sendto() failed, msg=%s \n", __LINE__, strerror (errno)); printf ("%3d: sendMessageToSocket() called for %s \n", __LINE__, myFD_Ctrl[senderEntryNum].name); keepGoing = false; } else { printf ("%3d: msg%d sent %s \n", __LINE__, myFD_Ctrl[entrySOCKET].msgNum, msg); } myFD_Ctrl[entrySOCKET].msgNum = myFD_Ctrl[entrySOCKET].msgNum < 99 ? myFD_Ctrl[entrySOCKET].msgNum + 1 : 1; return; } /*************************************************************************************************** * * * ATTENTION: this is a blocking func, should not be used in cooperative multitasking environment * ***************************************************************************************************/ char *lookup_host (char *foundIP, size_t bufSize, const char *host) { struct addrinfo hints, *res; int errcode; void *ptr; memset (&hints, 0, sizeof (hints)); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_STREAM; // SOCK_DGRAM is also possible hints.ai_flags |= AI_CANONNAME; errcode = getaddrinfo (host, NULL, &hints, &res); if (errcode != 0) { printf ("%03d: ERROR: getaddrinfo() returned an error, %s \n", __LINE__, gai_strerror(errcode)); return ""; } printf ("%03d: Host: %s \n", __LINE__, host); while (res) { inet_ntop (res->ai_family, res->ai_addr->sa_data, foundIP, bufSize); switch (res->ai_family) { case AF_INET: ptr = &((struct sockaddr_in *) res->ai_addr)->sin_addr; break; case AF_INET6: ptr = &((struct sockaddr_in6 *) res->ai_addr)->sin6_addr; break; } inet_ntop (res->ai_family, ptr, foundIP, bufSize); printf ("%03d: IPv%d address: %s (%s) \n", __LINE__, res->ai_family == PF_INET6 ? 6 : 4, foundIP, res->ai_canonname); res = res->ai_next; } freeaddrinfo (res); return foundIP; } // -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ // -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ // -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ /*************************************************************************************************** * * ***************************************************************************************************/ void setupSocketData (char *name, int entry, PROCESS_INPUT func) { myFD_Ctrl[entry].name = name; printf ("%03d: Connecting to %s, on port %d \n", __LINE__, serverIP_Addr, serverPORT_Num); if ( (myFD_Ctrl[entry].handle = socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1) { printf ("%03d: ERROR: %s, socket() setup call failed, msg=%s \n", __LINE__, myFD_Ctrl[entry].name, strerror (errno)); exit (5); } memset((char *) &myFD_Ctrl[entry].si_other, 0, sizeof (struct sockaddr_in)); myFD_Ctrl[entry].si_other.sin_family = AF_INET; myFD_Ctrl[entry].si_other.sin_port = htons(serverPORT_Num); if (inet_aton(serverIP_Addr , &myFD_Ctrl[entry].si_other.sin_addr) == 0) { printf ("%03d: ERROR: %s, inet_aton() failed, msg=%s \n", __LINE__, myFD_Ctrl[entry].name, strerror (errno)); exit(1); } myFD_Ctrl[entry].closeRequired = true; myFD_Ctrl[entry].slen = sizeof (struct sockaddr_in) ; myFD_Ctrl[entry].recv_len = 0; myFD_Ctrl[entry].msgNum = 1; myFD_Ctrl[entry].processInput = func; fds[entry].fd = myFD_Ctrl[entry].handle; fds[entry].events = POLLIN; return; } /*************************************************************************************************** * * ***************************************************************************************************/ void readSocketData (int entry, bool timeOut) { ssize_t ret; char *s; if (timeOut) { return; } // printf ("%3d: readSocketData() running\n", __LINE__); ret = read (myFD_Ctrl[entry].handle, myFD_Ctrl[entry].RX_Buf, BUFLEN-1); if (ret > 0) { myFD_Ctrl[entry].RX_Buf[ret] = '\0'; s = strchr (myFD_Ctrl[entry].RX_Buf, '\n'); if (s) *s = '\0'; printf ("%3d: %s input %d: [%s]\n", __LINE__, myFD_Ctrl[entry].name, ret, myFD_Ctrl[entry].RX_Buf); } else if (ret == 0) { printf ("%03d: ERROR: no bytes\n", __LINE__); } else { printf ("%03d: ERROR: read error on %s, msg=%s\n", __LINE__, myFD_Ctrl[entry].name, strerror (errno)); keepGoing = false; } return; } // -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ // -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ // -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ /*************************************************************************************************** * * ***************************************************************************************************/ void setupStdIn (char *name, int entry, int fd, PROCESS_INPUT func) { myFD_Ctrl[entry].name = name; myFD_Ctrl[entry].handle = fd; myFD_Ctrl[entry].recv_len = 0; myFD_Ctrl[entry].closeRequired = false; myFD_Ctrl[entry].processInput = func; fds[entry].fd = myFD_Ctrl[entry].handle; fds[entry].events = POLLIN; return; } /*************************************************************************************************** * * ***************************************************************************************************/ void readStdIn (int entry, bool timeOut) { ssize_t ret; char *s; if (timeOut) { // printf ("%03d: multitasking would go here\n", __LINE__); return; } // printf ("%3d: readStdIn() running", __LINE__); ret = read (myFD_Ctrl[entry].handle, myFD_Ctrl[entry].RX_Buf, BUFLEN-1); if (ret > 0) { myFD_Ctrl[entry].RX_Buf[ret] = '\0'; s = strchr (myFD_Ctrl[entry].RX_Buf, '\n'); if (s) *s = '\0'; printf ("%3d: %s input %d: [%s]\n", __LINE__, myFD_Ctrl[entry].name, ret, myFD_Ctrl[entry].RX_Buf); } else { printf ("%03d: ERROR: read error on %s\n", __LINE__, myFD_Ctrl[entry].name); keepGoing = false; return; } // printf ("%3d: readStdIn() complete, about to send message \n", __LINE__); if (myFD_Ctrl[entry].RX_Buf[0] == 'q') { sendMessageToSocket ("quit command", entry); keepGoing = false; return; } sendMessageToSocket (myFD_Ctrl[entry].RX_Buf, entry); return; } // -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ // -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ // -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ /*************************************************************************************************** * * ***************************************************************************************************/ void setupDigitialInput (char *name, int entry, PROCESS_INPUT func, int portNum) { int fd; char pathBuf[500]; char cmd[500]; int writeLen; struct stat sb; // ------------------ If /sys/* directory for this GPIO does not exist, tell the kernel to create it sprintf (pathBuf, "/sys/class/gpio/gpio%d", portNum); if (stat(pathBuf, &sb) == 0 && S_ISDIR(sb.st_mode)) { printf ("%3d: %s gpio already enabled\n", __LINE__, name); } else { sprintf (pathBuf, "/sys/class/gpio/export"); fd = open (pathBuf, O_WRONLY, 0666); if (fd == -1) { printf ("%3d: ERROR: open(%s) failed, msg=%s\n", __LINE__, pathBuf, strerror (errno)); exit (6); } writeLen = sprintf (cmd, "%d", portNum); write (fd, cmd, (ssize_t)writeLen); close (fd); } // ------------------ Set this GPIO entry to detect both rising/falling edges sprintf (pathBuf, "/sys/class/gpio/gpio%d/edge", portNum); fd = open (pathBuf, O_WRONLY, 0666); if (fd == -1) { printf ("%3d: ERROR: open(%s) failed, msg=%s\n", __LINE__, pathBuf, strerror (errno)); exit (6); } writeLen = sprintf (cmd, "both"); write (fd, cmd, (ssize_t)writeLen); close (fd); // Input is the default, but here is where you could set the IO direction // ------------------ Open file that contains the actual GPIO state sprintf (pathBuf, "/sys/class/gpio/gpio%d/value", portNum); fd = open (pathBuf, O_RDONLY /* | O_DIRECT */ ); if (fd == -1) { printf ("%3d: ERROR: open(%s) failed, msg=%s\n", __LINE__, pathBuf, strerror (errno)); exit (6); } printf ("%3d: setupDigitialInput() successfully opened [%s]\n", __LINE__, pathBuf); myFD_Ctrl[entry].name = name; myFD_Ctrl[entry].handle = fd; myFD_Ctrl[entry].recv_len = 0; myFD_Ctrl[entry].closeRequired = true; myFD_Ctrl[entry].processInput = func; fds[entry].fd = myFD_Ctrl[entry].handle; fds[entry].events = POLLPRI; return; } /*************************************************************************************************** * * ***************************************************************************************************/ void readDigitalInput (int entry, bool timeOut) { ssize_t ret; char *s; if (timeOut) { return; } // printf ("%3d: readDigitalInput() running\n", __LINE__); lseek (myFD_Ctrl[entry].handle, 0, SEEK_SET); // TODO: find out if I need this? ret = read (myFD_Ctrl[entry].handle, myFD_Ctrl[entry].RX_Buf, BUFLEN-1); if (ret > 0) { myFD_Ctrl[entry].RX_Buf[ret] = '\0'; s = strchr (myFD_Ctrl[entry].RX_Buf, '\n'); if (s) *s = '\0'; printf ("%3d: %s input %d: [%s]\n", __LINE__, myFD_Ctrl[entry].name, ret, myFD_Ctrl[entry].RX_Buf); } else if (ret == 0) { printf ("%03d: ERROR: on %s, no bytes, IGNORED\n", __LINE__, myFD_Ctrl[entry].name); return; } else { printf ("%03d: ERROR: read error on %s, msg=%s, IGNORED\n", __LINE__, myFD_Ctrl[entry].name, strerror (errno)); return; } // Construct and send the message char msgBuf[500]; int val; sscanf (myFD_Ctrl[entry].RX_Buf, "%d", &val); sprintf (msgBuf, "%s state %s", myFD_Ctrl[entry].name, val == 1 ? "on" : "off"); sendMessageToSocket (msgBuf, entry); return; } // -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ // -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ // -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ // -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ // -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ // -_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_ /*************************************************************************************************** * * ***************************************************************************************************/ int main (int argc, char *argv[]) { printf ("%s starting. Built on %s at %s\n", __FILE__, __DATE__, __TIME__); strcpy (serverName, "127.0.0.1"); strcpy (serverName, "45.55.156.55"); strcpy (serverName, "www.jep.cc"); lookup_host (serverIP_Addr, sizeof serverIP_Addr, serverName); // Strictly speaking we don't need these two (global variables are already zero), but // someday if we malloc() these two arrays then this would be necessary memset (myFD_Ctrl, 0, sizeof myFD_Ctrl); memset (fds, 0 , sizeof fds ); numActiveFDs = 0; /* * Setup the input channels/entries that we will be monitoring. We do no error checking * to stop our selves from running past end of the arrays. That's not necessaryly a great idea. * However a fancy program might want to simply reallocate the arrays instead of crashing. Test * program does not need such fancy stuff. */ entrySTDIN = numActiveFDs; setupStdIn ("stdin", numActiveFDs++, 0, readStdIn); // Standard input access entrySOCKET = numActiveFDs; setupSocketData ("socket", numActiveFDs++, readSocketData); // Socket setup setupDigitialInput ("Digitial66", numActiveFDs++, readDigitalInput, 66); setupDigitialInput ("Digitial67", numActiveFDs++, readDigitalInput, 67); // Core loop setup, then begin. Loop runs forever until its time to shutdown int rc; int entry; // Set to 1000+ if debuging the loop // If no background tasks exist/wanted then set to a large number and make the code strictly responsive to input // Small values allow background tasks to run frequently. Really fancy code will be constantly changing this. timeOutMilliSecs = 6000; keepGoing = true; // May be set to false by intHandler() when it time to shutdown, possibly others as well signal (SIGINT, intHandler); { char msgBuf[200], msgTimeStr[200]; time_t now_t = time(0); struct tm * now_tm = localtime( &now_t ); // sprintf (msgBuf, "%s is now running. %04d-%02d-%02d %02d:%02d:%02d", now_tm.year + 1900, now_tm->tm_mon + 1, now_tm->tm_mday, now_tm->hour, now_tm->min, strftime (msgTimeStr, sizeof msgTimeStr - 1, "%Y-%b-%d %X %z", now_tm); sprintf (msgBuf, "%s is now running. %s ", __FILE__, msgTimeStr); sendMessageToSocket (msgBuf, entrySTDIN); // Tell server we are awake, who we are } while (keepGoing) { rc = poll (fds, numActiveFDs, timeOutMilliSecs); if (rc < 0) { printf ("%03d: ERROR: poll error, msg=%s, aborting\n", __LINE__, strerror (errno)); return 88; } for (entry = 0; entry < numActiveFDs; entry++) { if (myFD_Ctrl[entry].processInput == NULL) { // This is a programmer error, abort to encourage them to fix it printf ("%03d: ERROR: processInput func was not defined for entry %d", __LINE__, entry); exit (5); } if (rc == 0) { myFD_Ctrl[entry].processInput (entry, true); // poll timed out, let handler decide if they care continue; } if (fds[entry].revents == 0) continue; // not for this slot/entry if (fds[entry].revents & POLLIN) { // STDIN and sockets produce these events when they have input for us to process // printf ("%03d: About to call input handler for %s\n", __LINE__, myFD_Ctrl[entry].name); myFD_Ctrl[entry].processInput (entry, false); continue; } if (fds[entry].revents & POLLPRI) { // The GPIO driver produces these when the input changes, I have no idea why // Some docs treat this behaviour as 'interrupt' driven I/O. That would not be my personal phrasing // printf ("%03d: About to call input handler for %s\n", __LINE__, myFD_Ctrl[entry].name); myFD_Ctrl[entry].processInput (entry, false); continue; } printf ("%03d: ERROR: revents = %s\n", __LINE__, decodeEventsMask (fds[entry].revents) ); if (fds[entry].revents & POLLERR) { // Generally when we have been here its pathalogical, so aborting makes sense printf ("%03d: ERROR: poll error %s, msg=%s, aborting\n", __LINE__, myFD_Ctrl[entry].name, strerror (errno)); exit (4); } } } // When we drop out of the main loop we are shutting down. Clean up a few things. for (entry = 0; entry < numActiveFDs; entry++) { if (myFD_Ctrl[entry].closeRequired) close(myFD_Ctrl[entry].handle); } return 0; }
the_stack_data/708700.c
/* Copyright (c) 2014, Trail of Bits All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of Trail of Bits nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> extern void doTest(void); int main(int argc, char *argv[]) { doTest(); return 0; }
the_stack_data/11074795.c
int main() { return '\\'; }
the_stack_data/104829119.c
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 OR MIT #include <stdint.h> #include <assert.h> #include <stdlib.h> #include <string.h> // This Vector stub implementation is supposed to work with c_vec.rs. Please // refer to that file for a detailed explanation about the workings of this // abstraction. Public methods implemented in c_vec.rs act as wrappers around // methods implemented here. // __CPROVER_max_malloc_size is dependent on the number of offset bits used to // represent a pointer variable. By default, this is chosen to be 56, in which // case the max_malloc_size is 2 ** (offset_bits - 1). We could go as far as to // assign the default capacity to be the max_malloc_size but that would be overkill. // Instead, we choose a high-enough value 2 ** 10. Another reason to do // this is that it would be easier for the solver to reason about memory if multiple // Vectors are initialized by the abstraction consumer. // // For larger array sizes such as 2 ** (31 - 1) we encounter "array size too large // for flattening" error. #define DEFAULT_CAPACITY 1024 #define MAX_MALLOC_SIZE 18014398509481984 // A Vector is a dynamically growing array type with contiguous memory. We track // allocated memory, the length of the Vector and the capacity of the // allocation. // As can be seen from the pointer to mem (unint32_t*), we track memory in terms // of words. The current implementation works only if the containing type is // u32. This was specifically chosen due to a use case seen in the Firecracker // codebase. This structure is used to communicate over the FFI boundary. // Future work: // Ideally, the pointer to memory would be uint8_t* - representing that we treat // memory as an array of bytes. This would allow us to be generic over the type // of the element contained in the Vector. In that case, we would have to treat // every sizeof(T) bytes as an indivdual element and cast memory accordingly. typedef struct { uint32_t* mem; size_t len; size_t capacity; } vec; // The grow operation resizes the vector and copies its original contents into a // new allocation. This is one of the more expensive operations for the solver // to reason about and one way to get around this problem is to use a large // allocation size. We also implement sized_grow which takes a argument // definining the minimum number of additional elements that need to be fit into // the Vector memory. This aims to replicate behavior as seen in the Rust // standard library where the size of the vector is decided based on the // following equation: // new_capacity = max(capacity * 2, capacity + additional). // Please refer to method amortized_grow in raw_vec.rs in the Standard Library // for additional information. // The current implementation performance depends on CBMCs performance about // reasoning about realloc. If CBMC does better, do would we in the case of // this abstraction. // // One important callout to make here is that because we allocate a large enough // buffer, we cant reason about buffer overflow bugs. This is because the // allocated memory will (most-likely) always have enough space allocated after // the required vec capacity. // // Future work: // Ideally, we would like to get around the issue of resizing altogether since // CBMC supports unbounded arrays. In that case, we would allocate memory of // size infinity and work with that. For program verification, this would // optimize a lot of operations since the solver does not really have to worry // about the bounds of memory. The appropriate constant for capacity would be // __CPROVER_constant_infinity_uint but this is currently blocked due to // incorrect translation of the constant: https://github.com/diffblue/cbmc/issues/6261. // // Another way to approach this problem would be to implement optimizations in // the realloc operation of CBMC. Rather than allocating a new memory block and // copying over elements, we can track only the end pointer of the memory and // shift it to track the new length. Since this behavior is that of the // allocator, the consumer of the API is blind to it. void vec_grow_exact(vec* v, size_t new_cap) { uint32_t* new_mem = (uint32_t* ) realloc(v->mem, new_cap * sizeof(*v->mem)); v->mem = new_mem; v->capacity = new_cap; } void vec_grow(vec* v) { size_t new_cap = v->capacity * 2; if (new_cap > MAX_MALLOC_SIZE) { // Panic if the new size requirement is greater than max size that can // be allocated through malloc. assert(0); } vec_grow_exact(v, new_cap); } void vec_sized_grow(vec* v, size_t additional) { size_t min_cap = v->capacity + additional; size_t grow_cap = v->capacity * 2; // This resembles the Rust Standard Library behavior - amortized_grow in // alloc/raw_vec.rs // // Reference: https://doc.rust-lang.org/src/alloc/raw_vec.rs.html#421 size_t new_cap = min_cap > grow_cap ? min_cap : grow_cap; if (new_cap > MAX_MALLOC_SIZE) { // Panic if the new size requirement is greater than max size that can // be allocated through malloc. assert(0); } vec_grow_exact(v, new_cap); } vec* vec_new() { vec *v = (vec *) malloc(sizeof(vec)); // Default size is DEFAULT_CAPACITY. We compute the maximum number of // elements to ensure that allocation size is aligned. size_t max_elements = DEFAULT_CAPACITY / sizeof(*v->mem); v->mem = (uint32_t *) malloc(max_elements * sizeof(*v->mem)); v->len = 0; v->capacity = max_elements; // Return a pointer to the allocated vec structure, which is used in future // callbacks. return v; } vec* vec_with_capacity(size_t capacity) { vec *v = (vec *) malloc(sizeof(vec)); if (capacity > MAX_MALLOC_SIZE) { // Panic if the new size requirement is greater than max size that can // be allocated through malloc. assert(0); } v->mem = (uint32_t *) malloc(capacity * sizeof(*v->mem)); v->len = 0; v->capacity = capacity; return v; } void vec_push(vec* v, uint32_t elem) { // If we have already reached capacity, resize the Vector before // pushing in new elements. if (v->len == v->capacity) { // Ensure that we have capacity to hold atleast one more element vec_sized_grow(v, 1); } v->mem[v->len] = elem; v->len += 1; } uint32_t vec_pop(vec* v) { assert(v->len > 0); v->len -= 1; return v->mem[v->len]; } void vec_append(vec* v1, vec* v2) { // Reserve enough space before adding in new elements. vec_sized_grow(v1, v2->len); // Perform a memcpy of elements which is cheaper than pushing each element // at once. memcpy(v1->mem + v1->len, v2->mem, v2->len * sizeof(*v2->mem)); v1->len = v1->len + v2->len; } size_t vec_len(vec* v) { return v->len; } size_t vec_cap(vec* v) { return v->capacity; } void vec_free(vec* v) { free(v->mem); free(v); }
the_stack_data/143029.c
int main() { int a[] = {1, 2, 3}; char b[] = "ab"; char c; int d; c = b[3]; d = a[2]; return 0; }
the_stack_data/22011550.c
/**~action~ * OpaqueAction [Class] * * Description * * An OpaqueAction is an Action whose functionality is not specified within UML. * * Diagrams * * Actions * * Generalizations * * Action * * Attributes * *  body : String [0..*] * * Provides a textual specification of the functionality of the Action, in one or more languages other than UML. * *  language : String [0..*] * * If provided, a specification of the language used for each of the body Strings. * * Association Ends * *  ♦ inputValue : InputPin [0..*]{subsets Action::input} (opposite A_inputValue_opaqueAction::opaqueAction) * * The InputPins providing inputs to the OpaqueAction. * *  ♦ outputValue : OutputPin [0..*]{subsets Action::output} (opposite * A_outputValue_opaqueAction::opaqueAction) * * The OutputPins on which the OpaqueAction provides outputs. * * Constraints * *  language_body_size * * If the language attribute is not empty, then the size of the body and language lists must be the same. * * inv: language->notEmpty() implies (_'body'->size() = language->size()) **/
the_stack_data/198581815.c
/*guess.c Written by Thien K. M. Bui Last editted 01/26/22 */ #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { unsigned int seed; printf("Enter the random seed: "); scanf("%u", &seed); // seed = time(NULL); srandom(seed); int random_number = random()%100 + 1; printf("%i\n", random_number); printf("Guess my number: "); int user_guess; int count = 1; scanf("%i", &user_guess); while (user_guess != random_number){ if(user_guess > random_number){ printf("Too high!\n"); printf("Guess my number: "); scanf("%i", &user_guess); }else{ printf("Too low!\n"); printf("Guess my number: "); scanf("%i", &user_guess); } count = count + 1; } printf("Correct!"); printf("Total guesses = %i\n", count); }
the_stack_data/225143497.c
#include <pthread.h> #include <stdio.h> #include <malloc.h> #include <time.h> #include <stdlib.h> #include <string.h> pthread_mutex_t lock; long long N, thread_num; long double pi; long long m = 0, n = 0; int BITS = 99999; struct position{ float x; float y; }; struct position* rands; void* handler(void* ID){ int id = (int)ID; int nums = N/thread_num; // calcuate probability N times int local_n = 0; int local_m = 0; int start = id * nums; int end = (id+1) * nums; for (int i = start; i < end; i++){ float x = rands[i].x; float y = rands[i].y; local_n++; if (x*x + y*y <= 1)local_m++; } // lock pthread_mutex_lock(&lock); n += local_n; m += local_m; // unlock pthread_mutex_unlock(&lock); } int main(int args, char* argc[]){ if (args < 2){ printf("Expected Arguments.\n"); return -1; } pi = 0; N = atoi(argc[1]); thread_num = atoi(argc[2]); pthread_t* threads = (pthread_t*)malloc(sizeof(pthread_t*) * thread_num); rands = (struct position*)malloc(sizeof(struct position) * N); srand(time(NULL)); for(int i = 0; i < N; i++){ float x = rand() % (BITS + 1) / (float)(BITS + 1); float y = rand() % (BITS + 1) / (float)(BITS + 1); rands[i].x = x; rands[i].y = y; } for (int i = 0; i < thread_num; i++){ pthread_create(&threads[i], NULL, handler, (void*)i); } for (int i = 0; i < thread_num; i++){ pthread_join(threads[i], NULL); } pi = 4*((m*1.0)/n); printf("pi: %.10LF\n",pi); }
the_stack_data/15762172.c
#include <stdio.h> int main () { unsigned int x = 0x12345678; char *c = (char*)&x; if (*c == 0x78) { printf("Little endian"); } else { printf("Big endian"); } return 0; }
the_stack_data/104828291.c
#include <stdio.h> #include <stdlib.h> #include <dlfcn.h> int add(int a, int b) { return a + b; } void test_dlopen_null() { void* handle = dlopen(NULL, RTLD_LAZY); if (!handle) { printf("dlopen(NULL) failed\n"); exit(1); } int (*f)(int, int) = dlsym(handle, "add"); if (!f) { printf("dlsym(handle, add) failed\n"); exit(2); } int a = 22; int b = 33; printf("add(%d, %d) = %d\n", a, b, f(a, b)); dlclose(handle); } void test_dlopen_libc() { void* handle = dlopen("libc.so.6", RTLD_LAZY); if (!handle) { printf("dlopen(libc.so.6) failed\n"); exit(1); } int (*f)(const char*) = dlsym(handle, "puts"); if (!f) { printf("dlsym(handle, puts) failed\n"); exit(2); } f("puts from dlopened libc"); dlclose(handle); } void test_dlsym_function() { void* handle = dlopen("sharedlib.so", RTLD_LAZY); if (!handle) { printf("dlopen(sharedlib.so) failed\n"); exit(1); } void (*f)() = dlsym(handle, "print"); if (!f) { printf("dlsym(handle, print) failed\n"); exit(2); } f(); dlclose(handle); } void test_dlsym_global_var() { void* handle = dlopen("sharedlib.so", RTLD_LAZY); if (!handle) { printf("dlopen(sharedlib.so) failed\n"); exit(1); } int* global_var = dlsym(handle, "global_var"); if (!global_var) { printf("dlsym(handle, global_var) failed\n"); exit(2); } printf("main: global_var == %d\n", *global_var); dlclose(handle); } void test_dlsym_tls_var() { void* handle = dlopen("sharedlib.so", RTLD_LAZY); if (!handle) { printf("dlopen(sharedlib.so) failed\n"); exit(1); } int* tls_var = dlsym(handle, "tls_var"); if (!tls_var) { printf("dlsym(handle, tls_var) failed\n"); exit(2); } printf("main: tls_var == %d\n", *tls_var); dlclose(handle); } int main() { test_dlopen_null(); test_dlopen_libc(); test_dlsym_function(); test_dlsym_global_var(); test_dlsym_tls_var(); }
the_stack_data/92328981.c
int main(void) { int i; if (i == 0) {i++; i++; return 1;} else { } if (i == 0) {i++; i++; } else { } if (i == 0) {i++; i++; } else { } if (i == 0) {i++; i++; } else { } if (i == 0) {i++; i++; } else { } if (i == 0) {i++; i++; } else { } if (i == 0) {i++; i++; } else { } U: if (i == 1) { L0: if (i < 4) goto L0; } else if (i == 2) { L1: if (i < 4) goto L1; } else if (i == 3) { L2: if (i < 4) goto L2; } else if (i == 4) { L3: if (i < 4) goto L3; } if (i == 1) { L10: if (i < 4) goto L10; } else if (i == 2) { L11: if (i < 4) goto L11; } else if (i == 3) { L12: if (i < 4) goto L12; } else if (i == 4) { L13: if (i < 4) goto L13; } if (i < 6) goto U; return 0; }
the_stack_data/184229.c
#include <stdio.h> int main() { //printf("Hello World! \n"); for (int i = 0; i < 10; printf("%d\n", i++)) { printf("<<<<<<\n"); } int i = 0; while (i < 10) { printf("%d\n", i++); } do { printf("%d\n", i--); } while (i > 0); }
the_stack_data/820873.c
/* ------------------------------------------------------------------------------- lookup3.c, by Bob Jenkins, May 2006, Public Domain. These are functions for producing 32-bit hashes for hash table lookup. hashword(), hashlittle(), hashlittle2(), hashbig(), mix(), and final() are externally useful functions. Routines to test the hash are included if SELF_TEST is defined. You can use this free for any purpose. It's in the public domain. It has no warranty. You probably want to use hashlittle(). hashlittle() and hashbig() hash byte arrays. hashlittle() is is faster than hashbig() on little-endian machines. Intel and AMD are little-endian machines. On second thought, you probably want hashlittle2(), which is identical to hashlittle() except it returns two 32-bit hashes for the price of one. You could implement hashbig2() if you wanted but I haven't bothered here. If you want to find a hash of, say, exactly 7 integers, do a = i1; b = i2; c = i3; mix(a,b,c); a += i4; b += i5; c += i6; mix(a,b,c); a += i7; final(a,b,c); then use c as the hash value. If you have a variable length array of 4-byte integers to hash, use hashword(). If you have a byte array (like a character string), use hashlittle(). If you have several byte arrays, or a mix of things, see the comments above hashlittle(). Why is this so big? I read 12 bytes at a time into 3 4-byte integers, then mix those integers. This is fast (you can do a lot more thorough mixing with 12*3 instructions on 3 integers than you can with 3 instructions on 1 byte), but shoehorning those bytes into integers efficiently is messy. ------------------------------------------------------------------------------- */ //#define SELF_TEST 1 #include <stdio.h> /* defines printf for tests */ #include <time.h> /* defines time_t for timings in the test */ #include <stdint.h> /* defines uint32_t etc */ #include <sys/param.h> /* attempt to define endianness */ #ifdef linux # include <endian.h> /* attempt to define endianness */ #endif /* * My best guess at if you are big-endian or little-endian. This may * need adjustment. */ #if (defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN) && \ __BYTE_ORDER == __LITTLE_ENDIAN) || \ (defined(i386) || defined(__i386__) || defined(__i486__) || \ defined(__i586__) || defined(__i686__) || defined(vax) || defined(MIPSEL)) # define HASH_LITTLE_ENDIAN 1 # define HASH_BIG_ENDIAN 0 #elif (defined(__BYTE_ORDER) && defined(__BIG_ENDIAN) && \ __BYTE_ORDER == __BIG_ENDIAN) || \ (defined(sparc) || defined(POWERPC) || defined(mc68000) || defined(sel)) # define HASH_LITTLE_ENDIAN 0 # define HASH_BIG_ENDIAN 1 #else # define HASH_LITTLE_ENDIAN 0 # define HASH_BIG_ENDIAN 0 #endif #define hashsize(n) ((uint32_t)1<<(n)) #define hashmask(n) (hashsize(n)-1) #define rot(x,k) (((x)<<(k)) | ((x)>>(32-(k)))) /* ------------------------------------------------------------------------------- mix -- mix 3 32-bit values reversibly. This is reversible, so any information in (a,b,c) before mix() is still in (a,b,c) after mix(). If four pairs of (a,b,c) inputs are run through mix(), or through mix() in reverse, there are at least 32 bits of the output that are sometimes the same for one pair and different for another pair. This was tested for: * pairs that differed by one bit, by two bits, in any combination of top bits of (a,b,c), or in any combination of bottom bits of (a,b,c). * "differ" is defined as +, -, ^, or ~^. For + and -, I transformed the output delta to a Gray code (a^(a>>1)) so a string of 1's (as is commonly produced by subtraction) look like a single 1-bit difference. * the base values were pseudorandom, all zero but one bit set, or all zero plus a counter that starts at zero. Some k values for my "a-=c; a^=rot(c,k); c+=b;" arrangement that satisfy this are 4 6 8 16 19 4 9 15 3 18 27 15 14 9 3 7 17 3 Well, "9 15 3 18 27 15" didn't quite get 32 bits diffing for "differ" defined as + with a one-bit base and a two-bit delta. I used http://burtleburtle.net/bob/hash/avalanche.html to choose the operations, constants, and arrangements of the variables. This does not achieve avalanche. There are input bits of (a,b,c) that fail to affect some output bits of (a,b,c), especially of a. The most thoroughly mixed value is c, but it doesn't really even achieve avalanche in c. This allows some parallelism. Read-after-writes are good at doubling the number of bits affected, so the goal of mixing pulls in the opposite direction as the goal of parallelism. I did what I could. Rotates seem to cost as much as shifts on every machine I could lay my hands on, and rotates are much kinder to the top and bottom bits, so I used rotates. ------------------------------------------------------------------------------- */ #define mix(a,b,c) \ { \ a -= c; a ^= rot(c, 4); c += b; \ b -= a; b ^= rot(a, 6); a += c; \ c -= b; c ^= rot(b, 8); b += a; \ a -= c; a ^= rot(c,16); c += b; \ b -= a; b ^= rot(a,19); a += c; \ c -= b; c ^= rot(b, 4); b += a; \ } /* ------------------------------------------------------------------------------- final -- final mixing of 3 32-bit values (a,b,c) into c Pairs of (a,b,c) values differing in only a few bits will usually produce values of c that look totally different. This was tested for * pairs that differed by one bit, by two bits, in any combination of top bits of (a,b,c), or in any combination of bottom bits of (a,b,c). * "differ" is defined as +, -, ^, or ~^. For + and -, I transformed the output delta to a Gray code (a^(a>>1)) so a string of 1's (as is commonly produced by subtraction) look like a single 1-bit difference. * the base values were pseudorandom, all zero but one bit set, or all zero plus a counter that starts at zero. These constants passed: 14 11 25 16 4 14 24 12 14 25 16 4 14 24 and these came close: 4 8 15 26 3 22 24 10 8 15 26 3 22 24 11 8 15 26 3 22 24 ------------------------------------------------------------------------------- */ #define final(a,b,c) \ { \ c ^= b; c -= rot(b,14); \ a ^= c; a -= rot(c,11); \ b ^= a; b -= rot(a,25); \ c ^= b; c -= rot(b,16); \ a ^= c; a -= rot(c,4); \ b ^= a; b -= rot(a,14); \ c ^= b; c -= rot(b,24); \ } /* -------------------------------------------------------------------- This works on all machines. To be useful, it requires -- that the key be an array of uint32_t's, and -- that the length be the number of uint32_t's in the key The function hashword() is identical to hashlittle() on little-endian machines, and identical to hashbig() on big-endian machines, except that the length has to be measured in uint32_ts rather than in bytes. hashlittle() is more complicated than hashword() only because hashlittle() has to dance around fitting the key bytes into registers. -------------------------------------------------------------------- */ uint32_t hashword( const uint32_t *k, /* the key, an array of uint32_t values */ size_t length, /* the length of the key, in uint32_ts */ uint32_t initval) /* the previous hash, or an arbitrary value */ { uint32_t a,b,c; /* Set up the internal state */ a = b = c = 0xdeadbeef + (((uint32_t)length)<<2) + initval; /*------------------------------------------------- handle most of the key */ while (length > 3) { a += k[0]; b += k[1]; c += k[2]; mix(a,b,c); length -= 3; k += 3; } /*------------------------------------------- handle the last 3 uint32_t's */ switch(length) /* all the case statements fall through */ { case 3 : c+=k[2]; case 2 : b+=k[1]; case 1 : a+=k[0]; final(a,b,c); case 0: /* case 0: nothing left to add */ break; } /*------------------------------------------------------ report the result */ return c; } /* -------------------------------------------------------------------- hashword2() -- same as hashword(), but take two seeds and return two 32-bit values. pc and pb must both be nonnull, and *pc and *pb must both be initialized with seeds. If you pass in (*pb)==0, the output (*pc) will be the same as the return value from hashword(). -------------------------------------------------------------------- */ void hashword2 ( const uint32_t *k, /* the key, an array of uint32_t values */ size_t length, /* the length of the key, in uint32_ts */ uint32_t *pc, /* IN: seed OUT: primary hash value */ uint32_t *pb) /* IN: more seed OUT: secondary hash value */ { uint32_t a,b,c; /* Set up the internal state */ a = b = c = 0xdeadbeef + ((uint32_t)(length<<2)) + *pc; c += *pb; /*------------------------------------------------- handle most of the key */ while (length > 3) { a += k[0]; b += k[1]; c += k[2]; mix(a,b,c); length -= 3; k += 3; } /*------------------------------------------- handle the last 3 uint32_t's */ switch(length) /* all the case statements fall through */ { case 3 : c+=k[2]; case 2 : b+=k[1]; case 1 : a+=k[0]; final(a,b,c); case 0: /* case 0: nothing left to add */ break; } /*------------------------------------------------------ report the result */ *pc=c; *pb=b; } /* ------------------------------------------------------------------------------- hashlittle() -- hash a variable-length key into a 32-bit value k : the key (the unaligned variable-length array of bytes) length : the length of the key, counting by bytes initval : can be any 4-byte value Returns a 32-bit value. Every bit of the key affects every bit of the return value. Two keys differing by one or two bits will have totally different hash values. The best hash table sizes are powers of 2. There is no need to do mod a prime (mod is sooo slow!). If you need less than 32 bits, use a bitmask. For example, if you need only 10 bits, do h = (h & hashmask(10)); In which case, the hash table should have hashsize(10) elements. If you are hashing n strings (uint8_t **)k, do it like this: for (i=0, h=0; i<n; ++i) h = hashlittle( k[i], len[i], h); By Bob Jenkins, 2006. [email protected]. You may use this code any way you wish, private, educational, or commercial. It's free. Use for hash table lookup, or anything where one collision in 2^^32 is acceptable. Do NOT use for cryptographic purposes. ------------------------------------------------------------------------------- */ uint32_t hashlittle( const void *key, size_t length, uint32_t initval) { uint32_t a,b,c; /* internal state */ union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */ /* Set up the internal state */ a = b = c = 0xdeadbeef + ((uint32_t)length) + initval; u.ptr = key; if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) { const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */ const uint8_t *k8; /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */ while (length > 12) { a += k[0]; b += k[1]; c += k[2]; mix(a,b,c); length -= 12; k += 3; } /*----------------------------- handle the last (probably partial) block */ /* * "k[2]&0xffffff" actually reads beyond the end of the string, but * then masks off the part it's not allowed to read. Because the * string is aligned, the masked-off tail is in the same word as the * rest of the string. Every machine with memory protection I've seen * does it on word boundaries, so is OK with this. But VALGRIND will * still catch it and complain. The masking trick does make the hash * noticably faster for short strings (like English words). */ #ifndef VALGRIND switch(length) { case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break; case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break; case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break; case 8 : b+=k[1]; a+=k[0]; break; case 7 : b+=k[1]&0xffffff; a+=k[0]; break; case 6 : b+=k[1]&0xffff; a+=k[0]; break; case 5 : b+=k[1]&0xff; a+=k[0]; break; case 4 : a+=k[0]; break; case 3 : a+=k[0]&0xffffff; break; case 2 : a+=k[0]&0xffff; break; case 1 : a+=k[0]&0xff; break; case 0 : return c; /* zero length strings require no mixing */ } #else /* make valgrind happy */ k8 = (const uint8_t *)k; switch(length) { case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; case 11: c+=((uint32_t)k8[10])<<16; /* fall through */ case 10: c+=((uint32_t)k8[9])<<8; /* fall through */ case 9 : c+=k8[8]; /* fall through */ case 8 : b+=k[1]; a+=k[0]; break; case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */ case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */ case 5 : b+=k8[4]; /* fall through */ case 4 : a+=k[0]; break; case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */ case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */ case 1 : a+=k8[0]; break; case 0 : return c; } #endif /* !valgrind */ } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) { const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */ const uint8_t *k8; /*--------------- all but last block: aligned reads and different mixing */ while (length > 12) { a += k[0] + (((uint32_t)k[1])<<16); b += k[2] + (((uint32_t)k[3])<<16); c += k[4] + (((uint32_t)k[5])<<16); mix(a,b,c); length -= 12; k += 6; } /*----------------------------- handle the last (probably partial) block */ k8 = (const uint8_t *)k; switch(length) { case 12: c+=k[4]+(((uint32_t)k[5])<<16); b+=k[2]+(((uint32_t)k[3])<<16); a+=k[0]+(((uint32_t)k[1])<<16); break; case 11: c+=((uint32_t)k8[10])<<16; /* fall through */ case 10: c+=k[4]; b+=k[2]+(((uint32_t)k[3])<<16); a+=k[0]+(((uint32_t)k[1])<<16); break; case 9 : c+=k8[8]; /* fall through */ case 8 : b+=k[2]+(((uint32_t)k[3])<<16); a+=k[0]+(((uint32_t)k[1])<<16); break; case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */ case 6 : b+=k[2]; a+=k[0]+(((uint32_t)k[1])<<16); break; case 5 : b+=k8[4]; /* fall through */ case 4 : a+=k[0]+(((uint32_t)k[1])<<16); break; case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */ case 2 : a+=k[0]; break; case 1 : a+=k8[0]; break; case 0 : return c; /* zero length requires no mixing */ } } else { /* need to read the key one byte at a time */ const uint8_t *k = (const uint8_t *)key; /*--------------- all but the last block: affect some 32 bits of (a,b,c) */ while (length > 12) { a += k[0]; a += ((uint32_t)k[1])<<8; a += ((uint32_t)k[2])<<16; a += ((uint32_t)k[3])<<24; b += k[4]; b += ((uint32_t)k[5])<<8; b += ((uint32_t)k[6])<<16; b += ((uint32_t)k[7])<<24; c += k[8]; c += ((uint32_t)k[9])<<8; c += ((uint32_t)k[10])<<16; c += ((uint32_t)k[11])<<24; mix(a,b,c); length -= 12; k += 12; } /*-------------------------------- last block: affect all 32 bits of (c) */ switch(length) /* all the case statements fall through */ { case 12: c+=((uint32_t)k[11])<<24; case 11: c+=((uint32_t)k[10])<<16; case 10: c+=((uint32_t)k[9])<<8; case 9 : c+=k[8]; case 8 : b+=((uint32_t)k[7])<<24; case 7 : b+=((uint32_t)k[6])<<16; case 6 : b+=((uint32_t)k[5])<<8; case 5 : b+=k[4]; case 4 : a+=((uint32_t)k[3])<<24; case 3 : a+=((uint32_t)k[2])<<16; case 2 : a+=((uint32_t)k[1])<<8; case 1 : a+=k[0]; break; case 0 : return c; } } final(a,b,c); return c; } /* * hashlittle2: return 2 32-bit hash values * * This is identical to hashlittle(), except it returns two 32-bit hash * values instead of just one. This is good enough for hash table * lookup with 2^^64 buckets, or if you want a second hash if you're not * happy with the first, or if you want a probably-unique 64-bit ID for * the key. *pc is better mixed than *pb, so use *pc first. If you want * a 64-bit value do something like "*pc + (((uint64_t)*pb)<<32)". */ void hashlittle2( const void *key, /* the key to hash */ size_t length, /* length of the key */ uint32_t *pc, /* IN: primary initval, OUT: primary hash */ uint32_t *pb) /* IN: secondary initval, OUT: secondary hash */ { uint32_t a,b,c; /* internal state */ union { const void *ptr; size_t i; } u; /* needed for Mac Powerbook G4 */ /* Set up the internal state */ a = b = c = 0xdeadbeef + ((uint32_t)length) + *pc; c += *pb; u.ptr = key; if (HASH_LITTLE_ENDIAN && ((u.i & 0x3) == 0)) { const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */ const uint8_t *k8; /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */ while (length > 12) { a += k[0]; b += k[1]; c += k[2]; mix(a,b,c); length -= 12; k += 3; } /*----------------------------- handle the last (probably partial) block */ /* * "k[2]&0xffffff" actually reads beyond the end of the string, but * then masks off the part it's not allowed to read. Because the * string is aligned, the masked-off tail is in the same word as the * rest of the string. Every machine with memory protection I've seen * does it on word boundaries, so is OK with this. But VALGRIND will * still catch it and complain. The masking trick does make the hash * noticably faster for short strings (like English words). */ #ifndef VALGRIND switch(length) { case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; case 11: c+=k[2]&0xffffff; b+=k[1]; a+=k[0]; break; case 10: c+=k[2]&0xffff; b+=k[1]; a+=k[0]; break; case 9 : c+=k[2]&0xff; b+=k[1]; a+=k[0]; break; case 8 : b+=k[1]; a+=k[0]; break; case 7 : b+=k[1]&0xffffff; a+=k[0]; break; case 6 : b+=k[1]&0xffff; a+=k[0]; break; case 5 : b+=k[1]&0xff; a+=k[0]; break; case 4 : a+=k[0]; break; case 3 : a+=k[0]&0xffffff; break; case 2 : a+=k[0]&0xffff; break; case 1 : a+=k[0]&0xff; break; case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */ } #else /* make valgrind happy */ k8 = (const uint8_t *)k; switch(length) { case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; case 11: c+=((uint32_t)k8[10])<<16; /* fall through */ case 10: c+=((uint32_t)k8[9])<<8; /* fall through */ case 9 : c+=k8[8]; /* fall through */ case 8 : b+=k[1]; a+=k[0]; break; case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */ case 6 : b+=((uint32_t)k8[5])<<8; /* fall through */ case 5 : b+=k8[4]; /* fall through */ case 4 : a+=k[0]; break; case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */ case 2 : a+=((uint32_t)k8[1])<<8; /* fall through */ case 1 : a+=k8[0]; break; case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */ } #endif /* !valgrind */ } else if (HASH_LITTLE_ENDIAN && ((u.i & 0x1) == 0)) { const uint16_t *k = (const uint16_t *)key; /* read 16-bit chunks */ const uint8_t *k8; /*--------------- all but last block: aligned reads and different mixing */ while (length > 12) { a += k[0] + (((uint32_t)k[1])<<16); b += k[2] + (((uint32_t)k[3])<<16); c += k[4] + (((uint32_t)k[5])<<16); mix(a,b,c); length -= 12; k += 6; } /*----------------------------- handle the last (probably partial) block */ k8 = (const uint8_t *)k; switch(length) { case 12: c+=k[4]+(((uint32_t)k[5])<<16); b+=k[2]+(((uint32_t)k[3])<<16); a+=k[0]+(((uint32_t)k[1])<<16); break; case 11: c+=((uint32_t)k8[10])<<16; /* fall through */ case 10: c+=k[4]; b+=k[2]+(((uint32_t)k[3])<<16); a+=k[0]+(((uint32_t)k[1])<<16); break; case 9 : c+=k8[8]; /* fall through */ case 8 : b+=k[2]+(((uint32_t)k[3])<<16); a+=k[0]+(((uint32_t)k[1])<<16); break; case 7 : b+=((uint32_t)k8[6])<<16; /* fall through */ case 6 : b+=k[2]; a+=k[0]+(((uint32_t)k[1])<<16); break; case 5 : b+=k8[4]; /* fall through */ case 4 : a+=k[0]+(((uint32_t)k[1])<<16); break; case 3 : a+=((uint32_t)k8[2])<<16; /* fall through */ case 2 : a+=k[0]; break; case 1 : a+=k8[0]; break; case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */ } } else { /* need to read the key one byte at a time */ const uint8_t *k = (const uint8_t *)key; /*--------------- all but the last block: affect some 32 bits of (a,b,c) */ while (length > 12) { a += k[0]; a += ((uint32_t)k[1])<<8; a += ((uint32_t)k[2])<<16; a += ((uint32_t)k[3])<<24; b += k[4]; b += ((uint32_t)k[5])<<8; b += ((uint32_t)k[6])<<16; b += ((uint32_t)k[7])<<24; c += k[8]; c += ((uint32_t)k[9])<<8; c += ((uint32_t)k[10])<<16; c += ((uint32_t)k[11])<<24; mix(a,b,c); length -= 12; k += 12; } /*-------------------------------- last block: affect all 32 bits of (c) */ switch(length) /* all the case statements fall through */ { case 12: c+=((uint32_t)k[11])<<24; case 11: c+=((uint32_t)k[10])<<16; case 10: c+=((uint32_t)k[9])<<8; case 9 : c+=k[8]; case 8 : b+=((uint32_t)k[7])<<24; case 7 : b+=((uint32_t)k[6])<<16; case 6 : b+=((uint32_t)k[5])<<8; case 5 : b+=k[4]; case 4 : a+=((uint32_t)k[3])<<24; case 3 : a+=((uint32_t)k[2])<<16; case 2 : a+=((uint32_t)k[1])<<8; case 1 : a+=k[0]; break; case 0 : *pc=c; *pb=b; return; /* zero length strings require no mixing */ } } final(a,b,c); *pc=c; *pb=b; } /* * hashbig(): * This is the same as hashword() on big-endian machines. It is different * from hashlittle() on all machines. hashbig() takes advantage of * big-endian byte ordering. */ uint32_t hashbig( const void *key, size_t length, uint32_t initval) { uint32_t a,b,c; union { const void *ptr; size_t i; } u; /* to cast key to (size_t) happily */ /* Set up the internal state */ a = b = c = 0xdeadbeef + ((uint32_t)length) + initval; u.ptr = key; if (HASH_BIG_ENDIAN && ((u.i & 0x3) == 0)) { const uint32_t *k = (const uint32_t *)key; /* read 32-bit chunks */ const uint8_t *k8; /*------ all but last block: aligned reads and affect 32 bits of (a,b,c) */ while (length > 12) { a += k[0]; b += k[1]; c += k[2]; mix(a,b,c); length -= 12; k += 3; } /*----------------------------- handle the last (probably partial) block */ /* * "k[2]<<8" actually reads beyond the end of the string, but * then shifts out the part it's not allowed to read. Because the * string is aligned, the illegal read is in the same word as the * rest of the string. Every machine with memory protection I've seen * does it on word boundaries, so is OK with this. But VALGRIND will * still catch it and complain. The masking trick does make the hash * noticably faster for short strings (like English words). */ #ifndef VALGRIND switch(length) { case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; case 11: c+=k[2]&0xffffff00; b+=k[1]; a+=k[0]; break; case 10: c+=k[2]&0xffff0000; b+=k[1]; a+=k[0]; break; case 9 : c+=k[2]&0xff000000; b+=k[1]; a+=k[0]; break; case 8 : b+=k[1]; a+=k[0]; break; case 7 : b+=k[1]&0xffffff00; a+=k[0]; break; case 6 : b+=k[1]&0xffff0000; a+=k[0]; break; case 5 : b+=k[1]&0xff000000; a+=k[0]; break; case 4 : a+=k[0]; break; case 3 : a+=k[0]&0xffffff00; break; case 2 : a+=k[0]&0xffff0000; break; case 1 : a+=k[0]&0xff000000; break; case 0 : return c; /* zero length strings require no mixing */ } #else /* make valgrind happy */ k8 = (const uint8_t *)k; switch(length) /* all the case statements fall through */ { case 12: c+=k[2]; b+=k[1]; a+=k[0]; break; case 11: c+=((uint32_t)k8[10])<<8; /* fall through */ case 10: c+=((uint32_t)k8[9])<<16; /* fall through */ case 9 : c+=((uint32_t)k8[8])<<24; /* fall through */ case 8 : b+=k[1]; a+=k[0]; break; case 7 : b+=((uint32_t)k8[6])<<8; /* fall through */ case 6 : b+=((uint32_t)k8[5])<<16; /* fall through */ case 5 : b+=((uint32_t)k8[4])<<24; /* fall through */ case 4 : a+=k[0]; break; case 3 : a+=((uint32_t)k8[2])<<8; /* fall through */ case 2 : a+=((uint32_t)k8[1])<<16; /* fall through */ case 1 : a+=((uint32_t)k8[0])<<24; break; case 0 : return c; } #endif /* !VALGRIND */ } else { /* need to read the key one byte at a time */ const uint8_t *k = (const uint8_t *)key; /*--------------- all but the last block: affect some 32 bits of (a,b,c) */ while (length > 12) { a += ((uint32_t)k[0])<<24; a += ((uint32_t)k[1])<<16; a += ((uint32_t)k[2])<<8; a += ((uint32_t)k[3]); b += ((uint32_t)k[4])<<24; b += ((uint32_t)k[5])<<16; b += ((uint32_t)k[6])<<8; b += ((uint32_t)k[7]); c += ((uint32_t)k[8])<<24; c += ((uint32_t)k[9])<<16; c += ((uint32_t)k[10])<<8; c += ((uint32_t)k[11]); mix(a,b,c); length -= 12; k += 12; } /*-------------------------------- last block: affect all 32 bits of (c) */ switch(length) /* all the case statements fall through */ { case 12: c+=k[11]; case 11: c+=((uint32_t)k[10])<<8; case 10: c+=((uint32_t)k[9])<<16; case 9 : c+=((uint32_t)k[8])<<24; case 8 : b+=k[7]; case 7 : b+=((uint32_t)k[6])<<8; case 6 : b+=((uint32_t)k[5])<<16; case 5 : b+=((uint32_t)k[4])<<24; case 4 : a+=k[3]; case 3 : a+=((uint32_t)k[2])<<8; case 2 : a+=((uint32_t)k[1])<<16; case 1 : a+=((uint32_t)k[0])<<24; break; case 0 : return c; } } final(a,b,c); return c; } #ifdef SELF_TEST /* used for timings */ void driver1() { uint8_t buf[256]; uint32_t i; uint32_t h=0; time_t a,z; time(&a); for (i=0; i<256; ++i) buf[i] = 'x'; for (i=0; i<1; ++i) { h = hashlittle(&buf[0],1,h); } time(&z); if (z-a > 0) printf("time %d %.8x\n", z-a, h); } /* check that every input bit changes every output bit half the time */ #define HASHSTATE 1 #define HASHLEN 1 #define MAXPAIR 60 #define MAXLEN 70 void driver2() { uint8_t qa[MAXLEN+1], qb[MAXLEN+2], *a = &qa[0], *b = &qb[1]; uint32_t c[HASHSTATE], d[HASHSTATE], i=0, j=0, k, l, m=0, z; uint32_t e[HASHSTATE],f[HASHSTATE],g[HASHSTATE],h[HASHSTATE]; uint32_t x[HASHSTATE],y[HASHSTATE]; uint32_t hlen; printf("No more than %d trials should ever be needed \n",MAXPAIR/2); for (hlen=0; hlen < MAXLEN; ++hlen) { z=0; for (i=0; i<hlen; ++i) /*----------------------- for each input byte, */ { for (j=0; j<8; ++j) /*------------------------ for each input bit, */ { for (m=1; m<8; ++m) /*------------ for serveral possible initvals, */ { for (l=0; l<HASHSTATE; ++l) e[l]=f[l]=g[l]=h[l]=x[l]=y[l]=~((uint32_t)0); /*---- check that every output bit is affected by that input bit */ for (k=0; k<MAXPAIR; k+=2) { uint32_t finished=1; /* keys have one bit different */ for (l=0; l<hlen+1; ++l) {a[l] = b[l] = (uint8_t)0;} /* have a and b be two keys differing in only one bit */ a[i] ^= (k<<j); a[i] ^= (k>>(8-j)); c[0] = hashlittle(a, hlen, m); b[i] ^= ((k+1)<<j); b[i] ^= ((k+1)>>(8-j)); d[0] = hashlittle(b, hlen, m); /* check every bit is 1, 0, set, and not set at least once */ for (l=0; l<HASHSTATE; ++l) { e[l] &= (c[l]^d[l]); f[l] &= ~(c[l]^d[l]); g[l] &= c[l]; h[l] &= ~c[l]; x[l] &= d[l]; y[l] &= ~d[l]; if (e[l]|f[l]|g[l]|h[l]|x[l]|y[l]) finished=0; } if (finished) break; } if (k>z) z=k; if (k==MAXPAIR) { printf("Some bit didn't change: "); printf("%.8x %.8x %.8x %.8x %.8x %.8x ", e[0],f[0],g[0],h[0],x[0],y[0]); printf("i %d j %d m %d len %d\n", i, j, m, hlen); } if (z==MAXPAIR) goto done; } } } done: if (z < MAXPAIR) { printf("Mix success %2d bytes %2d initvals ",i,m); printf("required %d trials\n", z/2); } } printf("\n"); } /* Check for reading beyond the end of the buffer and alignment problems */ void driver3() { uint8_t buf[MAXLEN+20], *b; uint32_t len; uint8_t q[] = "This is the time for all good men to come to the aid of their country..."; uint32_t h; uint8_t qq[] = "xThis is the time for all good men to come to the aid of their country..."; uint32_t i; uint8_t qqq[] = "xxThis is the time for all good men to come to the aid of their country..."; uint32_t j; uint8_t qqqq[] = "xxxThis is the time for all good men to come to the aid of their country..."; uint32_t ref,x,y; uint8_t *p; printf("Endianness. These lines should all be the same (for values filled in):\n"); printf("%.8x %.8x %.8x\n", hashword((const uint32_t *)q, (sizeof(q)-1)/4, 13), hashword((const uint32_t *)q, (sizeof(q)-5)/4, 13), hashword((const uint32_t *)q, (sizeof(q)-9)/4, 13)); p = q; printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n", hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13), hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13), hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13), hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13), hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13), hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13)); p = &qq[1]; printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n", hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13), hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13), hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13), hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13), hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13), hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13)); p = &qqq[2]; printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n", hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13), hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13), hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13), hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13), hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13), hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13)); p = &qqqq[3]; printf("%.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x %.8x\n", hashlittle(p, sizeof(q)-1, 13), hashlittle(p, sizeof(q)-2, 13), hashlittle(p, sizeof(q)-3, 13), hashlittle(p, sizeof(q)-4, 13), hashlittle(p, sizeof(q)-5, 13), hashlittle(p, sizeof(q)-6, 13), hashlittle(p, sizeof(q)-7, 13), hashlittle(p, sizeof(q)-8, 13), hashlittle(p, sizeof(q)-9, 13), hashlittle(p, sizeof(q)-10, 13), hashlittle(p, sizeof(q)-11, 13), hashlittle(p, sizeof(q)-12, 13)); printf("\n"); /* check that hashlittle2 and hashlittle produce the same results */ i=47; j=0; hashlittle2(q, sizeof(q), &i, &j); if (hashlittle(q, sizeof(q), 47) != i) printf("hashlittle2 and hashlittle mismatch\n"); /* check that hashword2 and hashword produce the same results */ len = 0xdeadbeef; i=47, j=0; hashword2(&len, 1, &i, &j); if (hashword(&len, 1, 47) != i) printf("hashword2 and hashword mismatch %x %x\n", i, hashword(&len, 1, 47)); /* check hashlittle doesn't read before or after the ends of the string */ for (h=0, b=buf+1; h<8; ++h, ++b) { for (i=0; i<MAXLEN; ++i) { len = i; for (j=0; j<i; ++j) *(b+j)=0; /* these should all be equal */ ref = hashlittle(b, len, (uint32_t)1); *(b+i)=(uint8_t)~0; *(b-1)=(uint8_t)~0; x = hashlittle(b, len, (uint32_t)1); y = hashlittle(b, len, (uint32_t)1); if ((ref != x) || (ref != y)) { printf("alignment error: %.8x %.8x %.8x %d %d\n",ref,x,y, h, i); } } } } /* check for problems with nulls */ void driver4() { uint8_t buf[1]; uint32_t h,i,state[HASHSTATE]; buf[0] = ~0; for (i=0; i<HASHSTATE; ++i) state[i] = 1; printf("These should all be different\n"); for (i=0, h=0; i<8; ++i) { h = hashlittle(buf, 0, h); printf("%2ld 0-byte strings, hash is %.8x\n", i, h); } } void driver5() { uint32_t b,c; b=0, c=0, hashlittle2("", 0, &c, &b); printf("hash is %.8lx %.8lx\n", c, b); /* deadbeef deadbeef */ b=0xdeadbeef, c=0, hashlittle2("", 0, &c, &b); printf("hash is %.8lx %.8lx\n", c, b); /* bd5b7dde deadbeef */ b=0xdeadbeef, c=0xdeadbeef, hashlittle2("", 0, &c, &b); printf("hash is %.8lx %.8lx\n", c, b); /* 9c093ccd bd5b7dde */ b=0, c=0, hashlittle2("Four score and seven years ago", 30, &c, &b); printf("hash is %.8lx %.8lx\n", c, b); /* 17770551 ce7226e6 */ b=1, c=0, hashlittle2("Four score and seven years ago", 30, &c, &b); printf("hash is %.8lx %.8lx\n", c, b); /* e3607cae bd371de4 */ b=0, c=1, hashlittle2("Four score and seven years ago", 30, &c, &b); printf("hash is %.8lx %.8lx\n", c, b); /* cd628161 6cbea4b3 */ c = hashlittle("Four score and seven years ago", 30, 0); printf("hash is %.8lx\n", c); /* 17770551 */ c = hashlittle("Four score and seven years ago", 30, 1); printf("hash is %.8lx\n", c); /* cd628161 */ } int main() { driver1(); /* test that the key is hashed: used for timings */ driver2(); /* test that whole key is hashed thoroughly */ driver3(); /* test that nothing but the key is hashed */ driver4(); /* test hashing multiple buffers (all buffers are null) */ driver5(); /* test the hash against known vectors */ return 1; } #endif /* SELF_TEST */
the_stack_data/674128.c
#include <stdio.h> #include <stdlib.h> int main() { float nota1, nota2, nota3, media; printf("Digite o valor da nota 1:"); scanf("%f", &nota1); printf("Digite o valor da nota 2:"); scanf("%f", &nota2); printf("Digite o valor da nota 3:"); scanf("%f", &nota3); media = (nota1 + nota2 + nota3)/3; printf("%f",media); getch(); return 0; // }
the_stack_data/218892186.c
// EXPECT: 8 int main() { int* p = alloc_pair(3, 5); return *p + *(p + 1); }
the_stack_data/73392.c
//DayOfProgrammer Solution by Akshat Pandey #include <stdio.h> #include <stdlib.h> int main() { int year,leap=0; //initializing year and leap variable scanf("%d",&year); if (year%4==0) //checking if year is leap or not leap=1; if (year>1918){ if (year % 100==0) //an year divided by 100 is not leap year leap=0; if (year % 400==0) //an year divided by 400 is leap year leap=1; } if (year!=1918){ if(leap==0) printf("13.09.%d\n",year); else printf("12.09.%d\n",year); } else printf("26.09.%d\n",year); return 0; }
the_stack_data/176705322.c
#include <sys/types.h> #include <sys/time.h> #include <unistd.h> #include <stdio.h> int main(){ struct timeval t1, t2; float elapsedTime; // start timer gettimeofday(&t1, NULL); int x=getpid(); gettimeofday(&t2, NULL); // compute and print the elapsed time in millisec elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms printf("time taken = %f ms\n",elapsedTime); }
the_stack_data/200143878.c
/*x:y.c*/ #include<stdio.h> main() { int x, y; int a; int i; printf("Input a number, Please?\n"); printf("X = "); scanf("%d", &x); printf("Y = "); scanf("%d", &y); if(y == 0) printf(" The divided number is 0. "); else if (x % y ==0) printf(" X / Y = %d", x/y); else{ a = x / y; x = x % y; printf (" X / Y = %d.", a); for (i = 1; i <= 20; i++){ printf ("%d", (x * 10) / y); if ((x * 10) % y == 0) break; else x = (x * 10) % y; } } printf("\n"); }
the_stack_data/272916.c
#include<stdio.h> #define pi 3.14159 main() { double R; scanf("%lf",&R); printf("A=%.4lf\n",pi*R*R); }
the_stack_data/57950762.c
// merge_string_literals_2.c -- a test case for gold // Copyright 2013 Free Software Foundation, Inc. // Written by Alexander Ivchenko <[email protected]> // This file is part of gold. // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, // MA 02110-1301, USA. // The goal of this program is to check whether string literals from different // object files are merged together const char* bar2() { return "abcdefghijklmnopqrstuvwxyz0123456789"; } const char* bar2_short() { return "abcdef"; }
the_stack_data/754585.c
#include <stdio.h> int main(){ int cod1,num1,cod2,num2; float val1,val2,x; scanf("%d %d %f",&cod1,&num1,&val1); scanf("%d %d %f",&cod2,&num2,&val2); x = (num1 * val1) + (num2 * val2); printf("VALOR A PAGAR: R$ %.2f\n",x); return 0; }
the_stack_data/29825318.c
//#include <stdio.h> #include <ncurses.h> #include <stdlib.h> #include <time.h> #include <endian.h> #include <string.h> #include <stdint.h> #include <limits.h> #include <unistd.h> #define MAX_ROOMS 12 #define MIN_ROOMS 6 #define xlenMax 78 #define ylenMax 19 #define minRoomxlen 4 #define minRoomylen 3 #define maxStairs 3 #define minStairs 1 #define BIT_SMART 0x1 #define TELE 0x2 #define TUN 0x4 #define ERAT 0x8 /*the room is a struct to save the relevant coordinates and leghts of a room*/ typedef struct room { int xloc; int yloc; int xlen; int ylen; }room; /*node - this contains x and y coordinates and address of next and prev node;*/ typedef struct node { int xcoor; int ycoor; struct node* prev; struct node* next; } node; /*node_heap - this contains the head node address (last node entered), the tail node address (first node entered) and the size of the node_heap*/ typedef struct node_heap { node* head; node* tail; int size; } node_heap; /*neighbourhood - this contains an 8x2 array that contains all possible neighour's coordinates (x,y) and the size - num of neighours*/ typedef struct neighbourhood{ int store[8][2]; int size; }neighbourhood; /*This struct will contain all the data we will need for pc*/ typedef struct PC{ int speed; int x; int y; }PC; /*ALL non-pc players data will be stored here*/ typedef struct NPC{ uint8_t character; int x; int y; int speed; int ifPCseen; int PCx; int PCy; }NPC; /*These nodes store all the players and their data needed to put them on the heap*/ typedef struct player_node{ int ifPC; PC* pc; NPC* npc; int next_turn; int when_initiated; int alive; struct player_node* prev; struct player_node* next; }player_node; /*This merely contains the head and tail player_node of the heap. It is used to access all the players*/ typedef struct player_node_heap { player_node* head; player_node* tail; //int size; } player_node_heap; int random_generator(player_node_heap** h, PC** pc, int nummon, room** rooms); int getmonsterlist(player_node_heap* h); int getkey(int x,int y, int *nextx, int *nexty, int* ifend, player_node_heap* h); void init_terminal(); int print_end(int success); int populate_heap(player_node_heap** h);//This puts all the player_node in a heap int push_player_node(player_node_heap* h, player_node* p);//used to add players to heap int kill_all();//This is used to make sure all the players malloc'd get freed int initialize_pc(PC** p);//this is used to take a pc struct's pointer and create a node and place it in random spot. int initialize_players(int n, PC* p);//used to create all the npc's as per the specs. /*These are all the prototypes that we'll use later*/ int getNeighbour(int x, int y, neighbourhood* n); int push(node_heap* nh, int x, int y); int pop(node_heap* nh, int* x, int* y); int print_difficulty(int PCposx, int PCposy, int diff_print[xlenMax][ylenMax]); int makes_sense(room rooms[], int numRooms); int not_so_rand_roomsize_resizer(int numRooms); int print_dungeon(); int djik (int xcoordinate, int ycoordinate, int ifdigger); int print_hardness(); int print_neighbour_movement(int PCposx, int PCposy, int hardness[xlenMax][ylenMax]); int next_move(player_node *pn, PC* pc, int* ifend, player_node_heap* h); int pop_player(player_node_heap* nh, int* ifend, player_node** p); int if_in_room(PC* pc);//updates all bots that share same room as pc uint8_t player_init_counter = 0; int distant_from_pc(PC* p, int x, int y);//creates a giant square centered at PC to make sure no bots are initialised too close /*the five grids are being saved so all the methods will have access to them*/ char grid[xlenMax][ylenMax]; int hardness[xlenMax][ylenMax]; int difficulty[xlenMax][ylenMax];//this will be used to save data for distance of non-tunnelers int difficulty_t[xlenMax][ylenMax];//this is to save data for tunnelers uint8_t shortPathRecord[xlenMax][ylenMax];//this keeps record of what is on the queue and what isn't for djik* algo player_node *grid_players[xlenMax][ylenMax];//this will be used to store pointers of all the player nodes int main(int argc, char* argv[]) { int i, j, x, y, k; //we declare most of the common variables we'll be using late //the grid below will be use to store all the characters for dungeon //char grid[xlenMax][ylenMax]; //int hardness[xlenMax][ylenMax]; int numRooms, numUpstairs, numDownstairs; uint8_t xPCpos, yPCpos; room *rooms; //first we populate the grid with spaces for (i = 0; i < xlenMax; i++) { for (j = 0; j < ylenMax; j++) { grid[i][j] = ' '; grid_players[i][j]=NULL; } } //load method goes ther for (i = 1; i < argc; i++) { if (!(strcmp(argv[i], "--load"))) { j = 1; break; } } if (j==1) { //printf("load found\n"); FILE *f; char *home = getenv("HOME"); char *gamedir = ".rlg327"; char *savefile = "dungeon"; char *path = malloc(strlen(home) + strlen(gamedir) + strlen(savefile) + 2 + 1); sprintf(path, "%s/%s/%s", home, gamedir, savefile); if( !( f = fopen( path, "r"))) {/*printf("Failed to open file\n");*/ return 1;} free(path); uint8_t temp8; uint16_t temp16; uint32_t temp32; char filetype[12]; fread(filetype, sizeof(char), 12, f); //dealing with version fread(&temp32, sizeof(temp32), 1, f); //dealing with filesize - will need to adjust endian if to be used fread(&temp32, sizeof(temp32), 1, f); //dealing xPCpos and yPCpos fread(&xPCpos, sizeof(uint8_t), 1, f); fread(&yPCpos, sizeof(uint8_t), 1, f); //now we populate the dungeon matrix for (j = 0; j < xlenMax + 2; j++) { fread(&temp8, sizeof(uint8_t), 1, f); } for (i = 0; i < ylenMax; i++) { fread(&temp8, sizeof(uint8_t), 1, f); for (j = 0; j < xlenMax; j++) { fread(&temp8, sizeof(uint8_t), 1, f); hardness[j][i] = temp8; } fread(&temp8, sizeof(uint8_t), 1, f); } for (j = 0; j < xlenMax + 2; j++) { fread(&temp8, sizeof(uint8_t), 1, f); } //end of hardness reading //number of Rooms are entered here fread(&temp16, sizeof(uint16_t), 1, f); numRooms = be16toh(temp16); //next we fill in the matrix rooms rooms = malloc(numRooms * sizeof(room)); //here we write the coordinates of the room for (i = 0; i < numRooms; i++) { fread(&temp8, sizeof(uint8_t), 1, f); rooms[i].xloc = temp8 - 1; fread(&temp8, sizeof(uint8_t), 1, f); rooms[i].yloc = temp8 - 1; fread(&temp8, sizeof(uint8_t), 1, f); rooms[i].xlen = temp8; fread(&temp8, sizeof(uint8_t), 1, f); rooms[i].ylen = temp8; } //next we populate the room area with the downstairs for (x = 0; x < numRooms; x++) { for (i = rooms[x].xloc; i < (rooms[x].xloc + rooms[x].xlen); i++) { for (j = rooms[x].yloc; j < (rooms[x].yloc + rooms[x].ylen); j++) { grid[i][j] = '.'; } } } //next we deal with upstairs fread(&temp16, sizeof(uint16_t), 1, f); numUpstairs = be16toh(temp16); for (i = 0; i < numUpstairs; i++) { fread(&temp8, sizeof(uint8_t), 1, f); x = temp8 - 1; fread(&temp8, sizeof(uint8_t), 1, f); y = temp8 - 1; grid[x][y] = '<'; } //next we deal with downstairs fread(&temp16, sizeof(uint16_t), 1, f); numDownstairs = be16toh(temp16); for (i = 0; i < numDownstairs; i++) { fread(&temp8, sizeof(uint8_t), 1, f); x = temp8 - 1; fread(&temp8, sizeof(uint8_t), 1, f); y = temp8 - 1; grid[x][y] = '>'; } //next we populate the corridors wherever hardness is zero and there is no room or stairs (or in this case wherever there is space in the grid) for (i = 0; i < ylenMax; i++) { for (j = 0; j < xlenMax; j++) { if (hardness[j][i] == 0) { if (grid[j][i] == ' ') grid[j][i] = '#'; } } } fclose(f); //printf("load found - final - no error while loading\n"); } //this is where we start processing the dungeon if the load was not found else { //we will start out by creating a seed with time-0 to access some randomeness srand(time(0)); //populating the hardness randomly for (i = 0; i < ylenMax; i++) { for (j = 0; j < xlenMax; j++) { hardness[j][i] = 1 + (rand() % 254); } } numRooms = MIN_ROOMS + (rand() % (MAX_ROOMS - MIN_ROOMS + 1)); rooms = malloc(numRooms * sizeof(room)); int resizer = not_so_rand_roomsize_resizer(numRooms);//we use this function to obtain a denominator to limit the size of the rooms //the if conditions used to obtain the max length of the room help avoid the floating point exception (core dump) later when we use it with modulus later int maxRoomxlen = xlenMax / resizer; if (maxRoomxlen <= minRoomxlen) maxRoomxlen = minRoomxlen + 1; int maxRoomylen = ylenMax / resizer; if (maxRoomylen <= minRoomylen) maxRoomylen = minRoomylen + 1; //printf("num Rooms = %d\n", numRooms); //uncomment to see num of rooms generated //this loop keeps going till random coordinates and lengths are obtained from random function that make sense while (1) { for (i = 0; i < numRooms; i++) { rooms[i].xloc = rand() % xlenMax; rooms[i].yloc = rand() % ylenMax; rooms[i].xlen = minRoomxlen + rand() % ((maxRoomxlen) - minRoomxlen); rooms[i].ylen = minRoomylen + rand() % ((maxRoomylen) - minRoomylen); } if (makes_sense(rooms, numRooms)) break; } //Next we populate the grid with '.' as per the randomised coordinates that made sense that we obtained earlier for (x = 0; x < numRooms; x++) { for (i = rooms[x].xloc; i < (rooms[x].xloc + rooms[x].xlen); i++) { for (j = rooms[x].yloc; j < (rooms[x].yloc + rooms[x].ylen); j++) { grid[i][j] = '.'; hardness[i][j] = 0; } } } //next we carve out a path between adjacent rooms in which we use the former's x coordinate and latter's y-coordinates to create a mid-point for (int x = 0; x < numRooms - 1; x++) { int middlex = rooms[x].xloc; int middley = rooms[x + 1].yloc; int i;//i will save the direction of the path if (rooms[x].yloc > middley) i = 1; else i = -1; //first we go from from midpoint to former room for ( j = middley; j != rooms[x].yloc; j += i) { if (grid[middlex][j] != '.') { grid[middlex][j] = '#'; hardness[middlex][j] = 0; } } //then we go from midpoint to latter room if (rooms[x + 1].xloc > middlex) i = 1; else i = -1; for ( j = middlex; j != rooms[x + 1].xloc; j += i) { if (grid[j][middley] != '.') { grid[j][middley] = '#'; hardness[j][middley] = 0; } } } //here we randomise the upwards and downward staircases and insert them wherever the random coordinates and its horizontal neighbours are part of room for (i = 0; i < 2; i++) { //first iteration adds random number of '<' to the grid, second adds '<' char staircase; if (i == 0) staircase = '<'; else staircase = '>'; int numStairs = minStairs + rand() % ((maxStairs) - minStairs); if (i == 0) { staircase = '<'; numUpstairs = numStairs; } else { staircase = '>'; numDownstairs = numStairs; } for (j = 0; j < numStairs; j++) { //while loops below keeps going till a successfuk coordinate is found while (1) { x = 1 + (rand() % (xlenMax - 2));//this ensures that we're not on the left or the right edge because the condition below checks horizontal neighbours y = (rand() % (ylenMax)); if (grid[x][y] == '.' && grid[x - 1][y] == '.' && grid[x + 1][y] == '.') { grid[x][y] = staircase; break; } } } } //this is where we try to position PC on the floor, making sure there's floor there xPCpos = 0; yPCpos = 0; for (i = 0; i < ylenMax; i++) { k = 0; for (j = 0; j < xlenMax; j++) { if (grid[j][i] == '.') { xPCpos = j+1; yPCpos = i+1; k=1; break; } } if (k) break; } } //this is where processing of the dungeon ends /*the method below will help produce the desired result for 1.04*/ //printf("\nPC is at (y, x): %d, %d\n\n", yPCpos, xPCpos); //below is where we print out the actual grid //print_dungeon(); //here we get the argument for the number of monsters j = 0; for (i = 1; i < argc; i++) { if (!(strcmp(argv[i], "--nummon"))) { j = 1; break; } } if (j) j = atoi(argv[i+1]); else j = 10; //processing for nummon tags beings here //printf("\n\n\n"); PC* pc; initialize_pc(&pc);//this is where pc gets initialised //printf("\nPC has been initialised; the coordinates accessible from main are %d, %d\n", pc->x, pc->y); initialize_players(j, pc);//this initialises all the bots player_node_heap* h; populate_heap(&h);//all monsters and pc get loaded on a heap init_terminal(); print_dungeon(); i = 0; player_node* curr = NULL; while (!(i)) { pop_player(h, &i, &curr);//this is where a node 'curr' gets selected to make next move if (!(i))//if its not the case that theres only one player left, then game goes on or else pc wins { next_move(curr, pc ,&i, h);//move prints and adds a 0.25s sleep as well /*Below the whole heap can be made visible for debugging*/ // while(curr2!=NULL) // player_node* curr2= h->head; // { // printf("%d-%d->",curr2->next_turn, curr2->ifPC); // curr2 = curr2->next; // } // printf("\n"); //if i=15..random_generator(&h, &pc, j); ->free heap. kill_all, {generate new dungeon} initialise pc. initialise players } if (i == 15) { random_generator(&h, &pc, j, &rooms); i=0; } } if (i==2){ print_dungeon(); usleep(2000000); print_end(0);//printf("\n\n\n\n\n\n\n\n\n\n\n\nPC LOST\n\n\n\n\n\n\n\n"); } else if (i==3)print_end(1);//printf("\n\n\n\n\n\n\n\n\n\n\n\nPC WON\n\n\n\n\n\n\n\n"); else if (i==5) print_end(5);///prints quit endwin(); kill_all(); free(h); //Now we check to see if there's a save switch to update the /.rlg327/dungeon j = 0; for (i = 1; i < argc; i++) { if (!(strcmp(argv[i], "--save"))) { j = 1; break; } } //processing for save tags beings here if (j) { //printf("save found\n"); FILE *f; char *home = getenv("HOME"); char *gamedir = ".rlg327"; char *savefile = "dungeon"; char *path = malloc(strlen(home) + strlen(gamedir) + strlen(savefile) + 2 + 1); sprintf(path, "%s/%s/%s", home, gamedir, savefile); if( !( f = fopen( path, "w"))) {printf("Failed to open file\n"); return 1;} free(path); char* marker = "RLG327-S2021"; fwrite(marker, sizeof(char), 12, f); uint32_t version = 0; version = htobe32(version); fwrite(&version, sizeof(uint32_t), 1, f); //calculate the size of the file, meanwhile the size is taken to be zero uint32_t size = 1708 + (4 * numRooms) + (2 * (numUpstairs + numDownstairs)); size = htobe32(size); fwrite(&size, sizeof(uint32_t), 1, f); //now we enter position of the PC fwrite(&xPCpos, sizeof(uint8_t), 1, f); fwrite(&yPCpos, sizeof(uint8_t), 1, f); //next we write the dungeon matrix - we will have to artificially populate the file with max hardness on border uint8_t temp8; for (j = 0; j < xlenMax + 2; j++) { temp8 = 255; fwrite(&temp8, sizeof(uint8_t), 1, f); } for (i = 0; i < ylenMax; i++) { temp8 = 255; fwrite(&temp8, sizeof(uint8_t), 1, f); for (j = 0; j < xlenMax; j++) { temp8 = hardness[j][i]; fwrite(&temp8, sizeof(uint8_t), 1, f); } temp8 = 255; fwrite(&temp8, sizeof(uint8_t), 1, f); } for (j = 0; j < xlenMax + 2; j++) { temp8 = 255; fwrite(&temp8, sizeof(uint8_t), 1, f); } //number of Rooms are entered here uint16_t temp16 = numRooms; temp16 = htobe16(temp16); fwrite(&temp16, sizeof(uint16_t), 1, f); //mext we write the coordinates of the room for (i = 0; i < numRooms; i++) { temp8 = 1 + rooms[i].xloc; fwrite(&temp8, sizeof(uint8_t), 1, f); temp8 = 1 + rooms[i].yloc; fwrite(&temp8, sizeof(uint8_t), 1, f); temp8 = rooms[i].xlen; fwrite(&temp8, sizeof(uint8_t), 1, f); temp8 = rooms[i].ylen; fwrite(&temp8, sizeof(uint8_t), 1, f); } //here we process the number of upstairs temp16 = numUpstairs; temp16 = htobe16(temp16); fwrite(&temp16, sizeof(uint16_t), 1, f); //here we enter the coordinates of upstairs for (j = 0; j < ylenMax; j++) { for (k = 0; k < xlenMax; k++) { if (grid[k][j] == '<') { temp8 = k + 1; fwrite(&temp8, sizeof(uint8_t), 1, f); temp8 = j + 1; fwrite(&temp8, sizeof(uint8_t), 1, f); } } } //here we process the number of downstairs temp16 = numDownstairs; temp16 = htobe16(temp16); fwrite(&temp16, sizeof(uint16_t), 1, f); //here we enter the coordinates of downstairs for (j = 0; j < ylenMax; j++) { for (k = 0; k < xlenMax; k++) { if (grid[k][j] == '>') { temp8 = k + 1; fwrite(&temp8, sizeof(uint8_t), 1, f); temp8 = j + 1; fwrite(&temp8, sizeof(uint8_t), 1, f); } } } fclose(f); } //processing for save ends here free(rooms); return 0; } /*The first is the makes_sense function that takes the array of rooms and number of Rooms as the argument. It tries to see if the top edge of one room coincides with area occupied with all the other rooms. This it does in four ways - first it check if the y coordinates of the top edge are inside the range+1(1 is added to keep a gap of 1) of the other rooms. If a room is coincides on the y-coordinates, then we check the x-coordinates. This we do in three ways, by checking the left corner, the right corner and the middle. If any of these indicate intersection then the program ends soonafter because it 'doesnt make sense' so the random function will pick some other coordinates. This function also makes sure the rooms are within the grid we have and don't exceed.*/ int makes_sense(room rooms[], int numRooms) { int checker = 1;//this essentially marks whether the program makes any sense, 0 indicates it doesnn't for (int i = 0; i < numRooms; i++) { for (int j = 0; j < numRooms; j++) { if (i != j) { //first it check if the y coordinates of the top edge are inside the range+1(1 is added to keep a gap of 1) of the other rooms. If a room is coincides on the y-coordinates, then we check the x-coordinates if( rooms[i].yloc >= rooms[j].yloc && rooms[i].yloc <= (rooms[j].yloc + rooms[j].ylen + 1) ) { //If a room is coincides on the y-coordinates, then we check the x-coordinates by checking the left corner, the right corner and the middle. if( (rooms[i].xloc >= rooms[j].xloc &&//this checks left corner rooms[i].xloc <= (rooms[j].xloc + rooms[j].xlen + 1) ) || ( rooms[i].xloc + rooms[i].xlen >= rooms[j].xloc &&//this checks right corner rooms[i].xloc + rooms[i].xlen <= (rooms[j].xloc + rooms[j].xlen + 1) ) || ( rooms[i].xloc < rooms[j].xloc &&//this checks middle rooms[i].xloc + rooms[i].xlen > (rooms[j].xloc + rooms[j].xlen + 1) ) ) checker = 0; } } if (checker == 0) break;//this helps end the program soon if the coordinates don't make sense } if (//this condition just makes sure all the coordinates will map the rooms in the available grid (rooms[i].xloc + rooms[i].xlen > xlenMax - 1) || (rooms[i].yloc + rooms[i].ylen > ylenMax - 1) ) checker = 0; if (checker == 0) break;//this, along with the break above, ensures we swiftly end the program soon if the coordinates don't make sense } return checker; } /*The second function simply creates a number that we use as a denominator for calculating max_size of the rooms. The reason for this function was because the program took too long to find coordinates that made sense of number of rooms greater than 8. This restricts the random function a little bit more - hence the not_so_random part of the name.*/ int not_so_rand_roomsize_resizer(int numRooms) { int roomSizer = (numRooms/2) - 1; return roomSizer; } /* The print_dungeon method below simply takes the x and y coordinates of the PC to make sure the @ is at the right position*/ int print_dungeon() { int i, j, x;//x will serve as the top offset char npc2; x=1; //for (i = 0; i < xlenMax; i++) {printf("-");} //printf("\n"); for (i = 0; i < ylenMax; i++) { //printf("|"); for (j = 0; j < xlenMax; j++) { mvaddch(i+x,j, grid[j][i]); //if (grid_players[j][i]==NULL) printf("%c", grid[j][i]); if (grid_players[j][i]==NULL) mvaddch( i+x,j, grid[j][i]); else { if (grid_players[j][i]->ifPC==1) mvaddch(i+x,j, '@');//printf("@"); else { //char* store = sprintf("%x",(grid_players[j][i]->npc->character)); int npc = grid_players[j][i]->npc->character; if (npc <= 9){ npc2=npc+'0'; mvaddch(i+x,j, npc2); } else{ npc2 = npc+'a'-10; mvaddch(i+x,j, npc2); } } } } //printf("\n"); } refresh(); //for (i = 0; i < xlenMax; i++) {printf("-");} //printf("\n\n\n"); } /*This will be used to calculate the shortest distance for the monsters shortPathRecord keeps tab of what is inside the queue node_heap is used to keep all the coordinates in a priority queue the while loops keep doing till there's nothing left to process if the distance from current node is shorter than the one the neighbour cell has then it is checked if the neighbour is already on queue. If it isn't then its pushed on the priority queue The method takes the coordinates of PC as the argument and whether or not the distance that we're finding for is a digger or not*/ int djik (int xcoordinate, int ycoordinate, int ifdigger) { int i, j, k, x, y; //next we calculate shortest distance for non-tunnelers if(!(ifdigger)) { for (i = 0; i < ylenMax; i++){ for(j = 0; j < xlenMax; j++) difficulty[j][i] = INT_MAX; } } else { for (i = 0; i < ylenMax; i++){ for(j = 0; j < xlenMax; j++) difficulty_t[j][i] = INT_MAX; } } //first we initialise the set of shortPathRecord to zero so nothing is taken to be processed by djik algo for (i = 0; i < ylenMax; i++){ for (j = 0; j < xlenMax; j++) { shortPathRecord[j][i] = 0; } } node_heap* newH; newH = malloc(sizeof(node_heap)); newH->size = 0; newH->tail = NULL; newH->head = NULL; push (newH, xcoordinate, ycoordinate); shortPathRecord [xcoordinate][ycoordinate] = 1; difficulty[xcoordinate][ycoordinate] = 0; difficulty_t[xcoordinate][ycoordinate] = 0; while(newH->size > 0) { pop(newH, &i, &j); shortPathRecord [i][j] = 0; neighbourhood currN; getNeighbour(i, j, &currN); int init_diff; if (ifdigger) init_diff = difficulty_t[i][j]; else init_diff = difficulty[i][j]; int diff_curr_block; if (grid[i][j]== ' ') diff_curr_block = 1 + (hardness[i][j]/85); else diff_curr_block = 1; for (k = 0; k < currN.size; k++) { x = currN.store[k][0]; y = currN.store[k][1]; if (!(ifdigger)) { if (grid[x][y] != ' ') { //this is where we process the diggers if (difficulty[x][y] > (init_diff + diff_curr_block)) { difficulty[x][y] = init_diff + diff_curr_block; //check to see if it is already on the processed stack if (!shortPathRecord[x][y]) { push(newH, x, y); shortPathRecord[x][y] = 1; } } } } else { //this is where we process the diggers if (difficulty_t[x][y] > (init_diff + diff_curr_block)) { difficulty_t[x][y] = init_diff + diff_curr_block; //check to see if it is already on the processed stack if (!shortPathRecord[x][y]) { push(newH, x, y); shortPathRecord[x][y] = 1; } } } } } free(newH); return 0; } /*This looks up the coordinates of all the cells around the targeted one. The coordinates of the targeted cell and the neighbourgood that we need to populate*/ int getNeighbour(int x, int y, neighbourhood* n){ int i,j; int size = 0; int store[8][2]; //= n->store; //we start from the left and the move in the clockwise fashion if (x > 0) { store[size][0] = x - 1; store[size][1] = y; size++; } if ( (x > 0) && (y > 0) ){ store[size][0] = x - 1; store[size][1] = y - 1; size++; } if (y > 0) { store[size][0] = x; store[size][1] = y - 1; size++; } if ( (x < (xlenMax - 1)) && (y > 0) ){ store[size][0] = x + 1; store[size][1] = y - 1; size++; } if (x < (xlenMax - 1)) { store[size][0] = x + 1; store[size][1] = y; size++; } if ( (x < (xlenMax - 1)) && (y < (ylenMax - 1)) ){ store[size][0] = x + 1; store[size][1] = y + 1; size++; } if (y < (ylenMax - 1)) { store[size][0] = x; store[size][1] = y + 1; size++; } if ( (x > 0) && (y < (ylenMax - 1)) ){ store[size][0] = x - 1; store[size][1] = y + 1; size++; } //finally getting the copy in neighbourhood for (i = 0; i < 2; i++) { for (j = 0; j < size; j++){ n->store[j][i] = store[j][i]; } } n->size = size; return 0; } /*this method takes the coordinates of the cell and the heap that we're suppose to push them into. A new node will be created and pushed into being the head. If the size is zero, the head and tail will be the newNode. If it isnt, then its simply the head*/ int push(node_heap* nh, int x, int y) { node *newNode = malloc(sizeof(node)); newNode->xcoor = x; newNode->ycoor = y; newNode->next = NULL; if (!(nh->size)){ newNode->prev = NULL; nh->tail = newNode; nh->head = newNode; nh->size++; } else{ nh->head->next = newNode; newNode->prev = (nh->head); nh->head = newNode; nh->size++; } return 0; } /*This is used to save the results of the node on the tail in the integer addresses provided and then free the node in the tail*/ int pop(node_heap* nh, int* x, int* y) { if (nh->size == 1) { *x = nh->tail->xcoor; *y = nh->tail->ycoor; free(nh->tail); } else { node* temp; *x = nh->tail->xcoor; *y = nh->tail->ycoor; temp = nh->tail; nh->tail = nh->tail->next; nh->tail->prev = NULL; free(temp); } nh->size -= 1; return 0; } /*This method is used to make sure that monsters initialise away from PC and creates a 9x9 square centered at the pc where no npc can intialise*/ int distant_from_pc(PC* p, int x, int y){ int PCx,PCy; //printf("we're in distant method"); PCx = p->x; PCy=p->y; //printf("PC is at (%d,%d)", PCx,PCy); if ((x > (PCx+4))||(x < (PCx-4))) return 1; if ((y > (PCy+4))||(y < (PCy-4))) return 1; return 0; } /*this is used to take a pc struct's pointer and create a node and place it in random spot.*/ int initialize_pc(PC** pc) { (*pc) = malloc(sizeof(PC)); int i, j, k; i = 1; while (i) { k = rand()%xlenMax; j = rand()%ylenMax; if (grid[k][j] == '.') i = 0; } (*pc)->x = k; (*pc)->y = j; (*pc)->speed = 10; player_node* pn = malloc(sizeof(player_node)); pn->ifPC = 1; pn->alive = 1; pn->pc = (*pc); pn->next_turn = 0; pn->when_initiated = player_init_counter++; //printf("\nx: %d y: %d\n", k,j); grid_players[k][j] = pn; } /* This is used to create all the npc's as per the specs. There is a distance of atleast 4 from PC*/ int initialize_players(int n, PC* p) { int i, j, k , t; for (t = 0; t < n; t++) { NPC *npc = malloc(sizeof(NPC)); //printf("good so far\n"); i= 1; while (i) { k = rand()%xlenMax; j = rand()%ylenMax; //printf("---random find:: x is %d and y is %d\n", k,j); if (grid[k][j] == '.' && grid_players[k][j]==NULL && distant_from_pc(p, k, j)) i = 0; } //printf("here! after initialisation"); npc->x = k; npc->y = j; //printf("x is %d and y is %d\n", k,j); npc->character = rand()&0xf;//any character netween 0-15 npc->speed = 5+ (rand()&0xf);//speed randomly gets selected from 5-20 npc-> ifPCseen = 0; player_node* pn = malloc(sizeof(player_node)); pn->ifPC = 0; pn->alive = 1; pn->npc = npc; pn->next_turn = 0; pn->when_initiated = player_init_counter++; //printf("x: %d y: %d\n", k,j); grid_players[k][j] = pn; } } /*This is a clean-up mechanism that makes sure all remaining players(malloc'd) are freed.*/ int kill_all() { int i, j; for (i = 0; i < ylenMax; i++) { for (j = 0; j < xlenMax; j++) { if (grid_players[j][i]!=NULL) { if (grid_players[j][i]->ifPC) { int tempx = (grid_players[j][i]->pc->x); int tempy = (grid_players[j][i]->pc->y); free(grid_players[j][i]->pc); free(grid_players[j][i]); grid_players[tempx][tempy] = NULL; } else { int tempx = grid_players[j][i]->npc->x; int tempy = grid_players[j][i]->npc->y; free(grid_players[j][i]->npc); free(grid_players[j][i]); grid_players[tempx][tempy] = NULL; } } } } } /*populates our heap with all the players in the grid_players using the player_push method*/ int populate_heap(player_node_heap** h) { (*h) = malloc(sizeof(player_node_heap)); (*h)->head = NULL; (*h)->tail = NULL; for (int i = 0; i < ylenMax; i++) { for (int j = 0; j < xlenMax; j++) { if(grid_players[j][i]!=NULL) push_player_node((*h), grid_players[j][i]); } } } /*This is used to push all the new nodes into the heap*/ int push_player_node(player_node_heap* h, player_node* p) { if (h->head==NULL)//nothing in the heap { h->head = p; h->tail = p; p->prev = NULL; p->next = NULL; return 0; } else { h->tail->next = p; p->prev = h->tail; h->tail = p; p->next = NULL; return 0; } } /*This is used to select a node in the heap based on the specs (lowest -> next_turn, when_initiated) */ int pop_player(player_node_heap* nh, int* ifend, player_node** output) { player_node* p = nh->head; if(p==NULL) { *ifend = 1; return 0; } if(p->next==NULL) { *ifend = 3; return 0; } int min_turn = p->next_turn; int min_when_initiated = p->when_initiated; player_node* min_node = p; p = p->next; while(p!=NULL) { if ((p->next_turn) < min_turn) { min_node = p; min_when_initiated = p->when_initiated; min_turn = p->next_turn; } else if((p->next_turn) == min_turn) { if ((p->when_initiated) < min_when_initiated) { min_node = p; min_when_initiated = p->when_initiated; } } p = p->next; } //if p->ifpc then print dungeon //next_move(min_node, ifend); *output = min_node; return 0; } /*This is used to kill a player, remove it from the heap and free the malloc'd node*/ int kill_player(player_node* p, player_node_heap* h) { //player_node* previous = if ((p->prev)!=NULL) { if (p->next==NULL) p->prev->next = NULL; else p->prev->next = p->next; } else //this is a head { if (p->next==NULL) h->head = NULL; else h->head = p->next; } if ((p->next)!=NULL) { p->next->prev = p->prev; } else //this is tail { if (p->prev==NULL) h->tail =NULL; else h->tail = p->prev; } if (p->ifPC==1) { int tempx = p->pc->x; int tempy = p->pc->y; free(p->pc); free(p); grid_players[tempx][tempy] = NULL; } else { int tempx = p->npc->x; int tempy = p->npc->y; free(p->npc); free(p); grid_players[tempx][tempy] = NULL; } } /*This is used to figure out what to do with the node selected with pop_player. nextx, and nexty are set to current location of the bot and will determine where it moves next. This method first checks if bot is tele or not. If it is tele then ifPCseen gets updated to 1, and PCx and PCy get updated to current PC location. If not tele, then if_in_room updates to see if tele can see the PC. Then we check to see if bot it intelligent. If intelligent and if PC is seen- then we will use djik algo (based on PCx and PCy and if digger or not) then update nextx and nexty. If not intelligent, then if PC is seen, then bot moves the nextx, and nexty, horizontally and then vertically towards the location known to the bot. If the bot is erratic, then we check random, and there's a 50 percent chance neigbouring cell will be used for nextx or nexty, other 50percent chance, next coordinates remain unchanged. Then the nextx and nexty is processed - as per the specs. First we check if there's a bot sitting on the next coordinates. If there is (and it isn't the current one) then we kill it and remove it from the heap and the grid_players. If there is no bot- action will depend on whether it can tunnel and what the hardness is.*/ int next_move(player_node *pn, PC* pc, int* ifend, player_node_heap* h) { if (pn->ifPC==1) { //printf("\nPC's turn, score of %d \n", pn->next_turn); int nextx, nexty; print_dungeon(); getkey(pn->pc->x, pn->pc->y, &nextx, &nexty, ifend, h); //boundary check if (nextx < 0 || nextx >= xlenMax) nextx = pn->pc->x; if (nexty < 0 || nexty >= ylenMax) nexty = pn->pc->y; if ( (pn->pc->x!=nextx) || (pn->pc->y!=nexty) ) { if(grid_players[nextx][nexty]!=NULL) { kill_player(grid_players[nextx][nexty], h); } grid_players[pn->pc->x][pn->pc->y] = NULL; pn->pc->x = nextx; pn->pc->y = nexty; grid_players[pn->pc->x][pn->pc->y] = pn; //wall check if (grid[pn->pc->x][pn->pc->y] == ' ') { grid[pn->pc->x][pn->pc->y] = '#'; hardness[pn->pc->x][pn->pc->y] = 0; } } pn->next_turn = pn->next_turn + (1000/(pn->pc->speed)); print_dungeon(); //usleep(10000); return 0; // getNeighbour(pn->pc->x, pn->pc->y, n); // for (int i = 0; i < n->size; i++) // { // if(grid_players[n->store[i][0]][n->store[i][1]]!=NULL) // { // kill_player(grid_players[n->store[i][0]][n->store[i][1]], h); // //player_node* temp = pn; // grid_players[pn->pc->x][pn->pc->y] = NULL; // pn->pc->x = n->store[i][0]; // pn->pc->y = n->store[i][1]; // grid_players[n->store[i][0]][n->store[i][1]] = pn; // break; // } // } // // // pn->next_turn = pn->next_turn + (1000/(pn->pc->speed)); // usleep(250000); // print_dungeon(); // free(n); // //printf("\n\n\n"); // return 0; } //printf("\nNPC with a score of %d at x,y: %d,%d named %x, being moved to ",pn->next_turn, pn->npc->x,pn->npc->y,pn->npc->character); //now we've established that the node is not of PC int character = pn->npc->character; int x = pn->npc->x; int y = pn->npc->y; neighbourhood* n; n = malloc(sizeof(neighbourhood)); getNeighbour(x, y, n); //dijik(x,y); int nextx=x; int nexty=y; int cost = INT_MAX; if (character & TELE) { pn->npc->ifPCseen = 1; pn->npc->PCx = pc->x; pn->npc->PCy = pc->y; } else { if_in_room(pc);//this updates all the ifPCseen and coordinates in all the bots in the room with PC } if (character & BIT_SMART) { if (pn->npc->ifPCseen) { if (character & TUN) { djik(pn->npc->PCx, pn->npc->PCy, 1); for (int i = 0; i < n->size; i++) { if (difficulty_t[n->store[i][0]][n->store[i][1]] < cost) { nextx = n->store[i][0]; nexty = n->store[i][1]; cost = difficulty_t[n->store[i][0]][n->store[i][1]]; } } }else { djik(pn->npc->PCx, pn->npc->PCy, 0); for (int i = 0; i < n->size; i++) { if (difficulty_t[n->store[i][0]][n->store[i][1]] < cost) { nextx = n->store[i][0]; nexty = n->store[i][1]; cost = difficulty[n->store[i][0]][n->store[i][1]]; } } } } } else //dumb ones just move in a straight line towards pc location { if (pn->npc->ifPCseen) { if(x > pn->npc->PCx) { nextx = x - 1; } else if (x < pn->npc->PCx) { nextx = x + 1; } else if (y > pn->npc->PCy) { nexty = y - 1; } else if (y < pn->npc->PCy) { nexty = y + 1; } //else do nothing } } if (character & ERAT) { if (rand()& 0x1) { //printf(" --sorry randomiser activated-- "); int selector = rand() % (n->size); nextx = n->store[selector][0]; nexty = n->store[selector][1]; } } //printf("%d, %d\n",nextx, nexty); //nextx and nexty will be the positions we will use to determine where the monster goes if(grid_players[nextx][nexty]==NULL)//no players to kill { if(character & TUN) { if(grid[nextx][nexty]==' ' && hardness[nextx][nexty] > 85 ) { hardness[nextx][nexty] -= 85; } else { hardness[nextx][nexty] = 0; if(grid[nextx][nexty]==' ') grid[nextx][nexty] = '#'; //player_node* temp = grid_players[x][y]; grid_players[x][y] = NULL; pn->npc->x = nextx; pn->npc->y = nexty; grid_players[nextx][nexty] = pn; } } else { if(grid[nextx][nexty]!=' ') { //player_node* temp = grid_players[x][y]; grid_players[x][y] = NULL; pn->npc->x = nextx; pn->npc->y = nexty; grid_players[nextx][nexty] = pn; } } } else if (nextx!=x || nexty!=y)//we kill someone { if (grid_players[nextx][nexty]->ifPC==1) *ifend = 2; kill_player(grid_players[nextx][nexty], h); //player_node* temp = grid_players[x][y]; grid_players[x][y] = NULL; pn->npc->x = nextx; pn->npc->y = nexty; grid_players[nextx][nexty] = pn; } pn->next_turn += (1000/(pn->npc->speed)); free (n); return 0; } /*This methods identifies all the non-npc players in the room shared by PC, and updated the ifPCseen to PC's current location PCx and PCy for npc*/ int if_in_room(PC* pc) { int upper = pc->y; while(upper+1 < ylenMax && grid[pc->x][upper+1]!=' ') upper++; int lower = pc->y; while(lower > 0 && grid[pc->x][lower-1]!=' ') lower--; int right = pc->x; while(right+1 < xlenMax && grid[right+1][pc->y]!=' ') right++; int left = pc->x; while(left > 0 && grid[left-1][pc->y]!=' ') left--; for(int i = lower; i <= upper; i++) { for(int j = left; j <= right; j++) { if (grid_players[j][i]!=NULL){ if(!(grid_players[j][i]->ifPC==1)){ grid_players[j][i]->npc->ifPCseen = 1; grid_players[j][i]->npc->PCx = pc->x; grid_players[j][i]->npc->PCy = pc->y; } } } } } /*This will help initialise the screen so we can have see the game, with contant printf's*/ void init_terminal() { initscr(); raw(); noecho(); curs_set(0); keypad(stdscr, TRUE); } /*This is simply use to display msgs like 'You lose' or 'You win' or 'You quit'.*/ int print_end(int success) { for (int i = 0; i < ylenMax+1; i++){ for (int j = 0; j< xlenMax; j++){ mvaddch(i,j,' '); } } if (success==5) { char* win = "YOU QUIT!!!!!!!!!!!!!."; for (int i = 0; win[i]!='.'; i++) mvaddch(10, 30+i, win[i]); } else if (success==1) { char* win = "YOU WIN!!!!!!!!!!!!!."; for (int i = 0; win[i]!='.'; i++) mvaddch(10, 30+i, win[i]); } else { char* lose = "YOU LOSE!!!!!!!!!!!!!."; for (int i = 0; lose[i]!='.'; i++) mvaddch(10, 30+i, lose[i]); } refresh(); usleep(2000000); } /*This method was added to the nex_move method, where to determine next move, get key fetches a key and reacts accordingly*/ int getkey(int prevx,int prevy, int *x,int *y, int *endif, player_node_heap* h) { int i; chtype ch = getch(); /////////////////////////clearing the top msd board in case we need to give a msg after key is pressed////////// for (i = 0; i < xlenMax; i++) mvaddch(0,i,' '); ///////////////////// *x = prevx; *y = prevy; //mvaddch(*y, *x,' '); if (ch=='8'||ch=='k') --*y; else if (ch=='5'||ch==' '|| ch=='.'); else if (ch=='6'||ch=='l') ++*x; else if (ch=='4'||ch=='h') --*x; else if (ch=='2'||ch=='j') ++*y; else if (ch=='1'||ch=='b') {++*y; --*x;} else if (ch=='3'||ch=='n') {++*y; ++*x;} else if (ch=='7'||ch=='y') {--*x; --*y;} else if (ch=='9'||ch=='u') {--*y; ++*x;} else if (ch=='q'||ch=='Q') {*endif = 5;} else if (ch=='m'); else if (ch=='<') { if (grid[prevx][prevy]=='<') { *endif=15; } } else if (ch=='>') { if (grid[prevx][prevy]=='>') { *endif=15; } } //else if (ch=='q') endwin(); //game(y, x); //none of the recongnised keys were selected else { char* lose = "THE KEY WAS UNRECOGNISED, TRY AGAIN!."; for (i = 0; lose[i]!='.'; i++) mvaddch(0, i, lose[i]); refresh(); getkey(prevx, prevy, x,y, endif,h); } //boundary check - pc will get an error if it hits the boundary and and an opportunity to put in another key//// if (*x < 0 || *x >= xlenMax || *y < 0 || *y >= ylenMax)//boundary check { *x = prevx; *y = prevy; char* lose = "YOU HAVE HIT THE EDGE, YOU CANNOT GO ANY FURTHER."; for (i = 0; lose[i]!='.'; i++) mvaddch(0, i, lose[i]); refresh(); getkey(prevx, prevy, x,y, endif,h); } //if we come across a wall and since the player cannot tunnel, we ask for another key/// if(grid[*x][*y]==' ') { *x = prevx; *y = prevy; char* lose = "SORRY YOU CAN'T TUNNEL YOUR WAY THROUGH. YOU NEED TO FIND AN EXISTING TUNNEL!!."; for (i = 0; lose[i]!='.'; i++) mvaddch(0, i, lose[i]); refresh(); getkey(prevx, prevy, x,y, endif,h); } if (ch=='m') { getmonsterlist(h); getkey(prevx, prevy, x,y, endif,h); } } /*This method allows for the screen to show the monsters with their names/characters and their position relative to the pc*/ int getmonsterlist(player_node_heap* h) { player_node* current = (h->head); player_node* print_node; int left_offset = 3; int top_offset = 16; PC* pc; while (!(current->ifPC)) current=current->next; pc = current->pc; current = (h->head); while(1) { for (int j = left_offset-1; j < ylenMax-left_offset+1; j++) { for(int k = top_offset-1; k <xlenMax-top_offset; k++) mvaddch(j, k, ' '); } refresh(); //usleep(2000000); int count = 0; print_node = current; char* player_info_2 = "=============================================."; int cursor2; for ( cursor2 = 0; player_info_2[cursor2]!='.'; cursor2++) mvaddch(left_offset+count, top_offset+cursor2, player_info_2[cursor2]); count++; player_info_2 = "NPC LIST WITH CHARACTERS AND DISTANCE."; for ( cursor2 = 0; player_info_2[cursor2]!='.'; cursor2++) mvaddch(left_offset+count, top_offset+cursor2, player_info_2[cursor2]); count++; player_info_2 = "=============================================."; for ( cursor2 = 0; player_info_2[cursor2]!='.'; cursor2++) mvaddch(left_offset+count, top_offset+cursor2, player_info_2[cursor2]); count++; int counter2 = 0;//this stores the num of monsters on display while(print_node!= NULL && counter2 < 10) { if (!(print_node->ifPC)) { int cursor; char* player_info = "PLAYER ."; for (cursor = 0; player_info[cursor]!='.'; cursor++) mvaddch(left_offset+count, top_offset+cursor, player_info[cursor]); if (print_node->npc->character<10) mvaddch(left_offset+count, 17+cursor, print_node->npc->character + '0'); else mvaddch(left_offset+count, 17+cursor, print_node->npc->character + 'a'-10); cursor+=5; if (pc->y > print_node->npc->y) { if ((pc->y - print_node->npc->y) < 10) { cursor++; mvaddch(left_offset+count, 17+cursor, ('0' + pc->y - print_node->npc->y)); cursor++; }else{ mvaddch(left_offset+count, 17+cursor, ('0' + ((pc->y - print_node->npc->y)/10))); cursor++; mvaddch(left_offset+count, 17+cursor, ('0' + ((pc->y - print_node->npc->y)%10))); cursor++; } mvaddch(left_offset+count, 17+cursor, 'N'); cursor++; } else if (pc->y < print_node->npc->y) { if ((-pc->y + print_node->npc->y) < 10) { cursor++; mvaddch(left_offset+count, 17+cursor, ('0' - pc->y + print_node->npc->y)); cursor++; }else{ mvaddch(left_offset+count, 17+cursor, ('0' + ((-pc->y + print_node->npc->y)/10))); cursor++; mvaddch(left_offset+count, 17+cursor, ('0' + ((-pc->y + print_node->npc->y)%10))); cursor++; } mvaddch(left_offset+count, 17+cursor, 'S'); cursor++; } else cursor+=2; cursor+=4; if (pc->x > print_node->npc->x) { if ((pc->x - print_node->npc->x) < 10) { cursor++; mvaddch(left_offset+count, 17+cursor, ('0' + pc->x - print_node->npc->x)); cursor++; }else{ mvaddch(left_offset+count, 17+cursor, ('0' + ((pc->x - print_node->npc->x)/10))); cursor++; mvaddch(left_offset+count, 17+cursor, ('0' + ((pc->x - print_node->npc->x)%10))); cursor++; } mvaddch(left_offset+count, 17+cursor, 'W'); cursor++; } else if (pc->x < print_node->npc->x) { if ((-pc->x + print_node->npc->x) < 10) { cursor++; mvaddch(left_offset+count, 17+cursor, ('0' - pc->x + print_node->npc->x)); cursor++; }else{ mvaddch(left_offset+count, 17+cursor, ('0' + ((-pc->x + print_node->npc->x)/10))); cursor++; mvaddch(left_offset+count, 17+cursor, ('0' + ((-pc->x + print_node->npc->x)%10))); cursor++; } mvaddch(left_offset+count, 17+cursor, 'E'); cursor++; } count++; counter2++; print_node = print_node->next; } else print_node = print_node->next; } player_info_2 = "=============================================."; for ( cursor2 = 0; player_info_2[cursor2]!='.'; cursor2++) mvaddch(left_offset+count, top_offset+cursor2, player_info_2[cursor2]); refresh(); int key = getch(); if (key==27) {print_dungeon(); break;}//if ESC pressed else if (key == 259) //if UP key is pressed { if (current != NULL && current->prev) current = current->prev; } else if (key == 258)//if DOWN key is pressed { if (current != NULL && current->next) current = current->next; } } } /*This should ensure a completely random generated dungeon if the player takes the stairs */ int random_generator(player_node_heap** h, PC** pc, int nummon, room** rooms) { int i,j,x,y; for (i = 0; i < xlenMax; i++) { for (j = 0; j < ylenMax; j++) { grid[i][j] = ' '; grid_players[i][j]=NULL; } } //we will start out by creating a seed with time-0 to access some randomeness srand(time(0)); //populating the hardness randomly for (i = 0; i < ylenMax; i++) { for (j = 0; j < xlenMax; j++) { hardness[j][i] = 1 + (rand() % 254); } } int numRooms = MIN_ROOMS + (rand() % (MAX_ROOMS - MIN_ROOMS + 1)); *rooms = malloc(numRooms * sizeof(room)); int resizer = not_so_rand_roomsize_resizer(numRooms);//we use this function to obtain a denominator to limit the size of the rooms //the if conditions used to obtain the max length of the room help avoid the floating point exception (core dump) later when we use it with modulus later int maxRoomxlen = xlenMax / resizer; if (maxRoomxlen <= minRoomxlen) maxRoomxlen = minRoomxlen + 1; int maxRoomylen = ylenMax / resizer; if (maxRoomylen <= minRoomylen) maxRoomylen = minRoomylen + 1; //printf("num Rooms = %d\n", numRooms); //uncomment to see num of rooms generated //this loop keeps going till random coordinates and lengths are obtained from random function that make sense while (1) { for (i = 0; i < numRooms; i++) { (*rooms)[i].xloc = rand() % xlenMax; (*rooms)[i].yloc = rand() % ylenMax; (*rooms)[i].xlen = minRoomxlen + rand() % ((maxRoomxlen) - minRoomxlen); (*rooms)[i].ylen = minRoomylen + rand() % ((maxRoomylen) - minRoomylen); } if (makes_sense((*rooms), numRooms)) break; } //Next we populate the grid with '.' as per the randomised coordinates that made sense that we obtained earlier for (x = 0; x < numRooms; x++) { for (i = (*rooms)[x].xloc; i < ((*rooms)[x].xloc + (*rooms)[x].xlen); i++) { for (j = (*rooms)[x].yloc; j < ((*rooms)[x].yloc + (*rooms)[x].ylen); j++) { grid[i][j] = '.'; hardness[i][j] = 0; } } } //next we carve out a path between adjacent rooms in which we use the former's x coordinate and latter's y-coordinates to create a mid-point for (int x = 0; x < numRooms - 1; x++) { int middlex = (*rooms)[x].xloc; int middley = (*rooms)[x + 1].yloc; int i;//i will save the direction of the path if ((*rooms)[x].yloc > middley) i = 1; else i = -1; //first we go from from midpoint to former room for ( j = middley; j != (*rooms)[x].yloc; j += i) { if (grid[middlex][j] != '.') { grid[middlex][j] = '#'; hardness[middlex][j] = 0; } } //then we go from midpoint to latter room if ((*rooms)[x + 1].xloc > middlex) i = 1; else i = -1; for ( j = middlex; j != (*rooms)[x + 1].xloc; j += i) { if (grid[j][middley] != '.') { grid[j][middley] = '#'; hardness[j][middley] = 0; } } } //here we randomise the upwards and downward staircases and insert them wherever the random coordinates and its horizontal neighbours are part of room int numUpstairs, numDownstairs; for (i = 0; i < 2; i++) { //first iteration adds random number of '<' to the grid, second adds '<' char staircase; if (i == 0) staircase = '<'; else staircase = '>'; int numStairs = minStairs + rand() % ((maxStairs) - minStairs); if (i == 0) { staircase = '<'; numUpstairs = numStairs; } else { staircase = '>'; numDownstairs = numStairs; } for (j = 0; j < numStairs; j++) { //while loops below keeps going till a successfuk coordinate is found while (1) { x = 1 + (rand() % (xlenMax - 2));//this ensures that we're not on the left or the right edge because the condition below checks horizontal neighbours y = (rand() % (ylenMax)); if (grid[x][y] == '.' && grid[x - 1][y] == '.' && grid[x + 1][y] == '.') { grid[x][y] = staircase; break; } } } } //PC* pc; initialize_pc(pc);//this is where pc gets initialised //printf("\nPC has been initialised; the coordinates accessible from main are %d, %d\n", pc->x, pc->y); initialize_players(nummon, *pc);//this initialises all the bots //player_node_heap* h; populate_heap(h);//all monsters and pc get loaded on a heap print_dungeon(); }
the_stack_data/70450265.c
int mx_toupper(int c) { if (c >= 97 && c <= 122) { return c - 32; } else { return c; } }
the_stack_data/29824090.c
#include <setjmp.h> /** save program state **/ int _setjmp(jmp_buf env) { return setjmp(env); } /*** saves the current state, without the signal mask, of the calling environment in the TYPEDEF(jmp_buf) ARGUMENT(env). ***/ /* CONSTRAINT: entire controlling expression of a selection or iteration statement CONSTRAINT: one operand of a relational or equality operator which is the entire controlling expression of a selction or iteration statement CONSTRAINT: the operand of a unary ! as the entire controlling expression of a selection or iteration statement CONSTRAINT: an entire expression statement UNSPECIFIED(Whether THIS() is a macro or identifier with external linkage) UNDEFINED(A macro definition of THIS() is suppressed in order to access an actual function) UNDEFINED(A program defines an external identifier named LITERAL(setjmp)) XOPEN(400) XOBSOLETE(700, FUNCTION(siglongjmp)) */
the_stack_data/54825212.c
#include <stdio.h> #include <unistd.h> #include <sys/types.h> int main(int argc,char* argv[]) { int res; printf("Before fork():PID[%d]\n",getpid()); res = fork(); printf("The value of res is %d\n",res); if(res == 0) { printf("I am child! PID: [%d]\n",getpid()); } else { printf("I am parent! PID: [%d]\n",getpid()); } printf("Program Terminated!\n"); return 0; }
the_stack_data/193892146.c
/** * Test antidebug features * * Related projects, which detects virtualization: * * https://github.com/a0rtega/pafish/tree/master/pafish Pafish * * Other links: * * http://pferrie.host22.com/papers/antidebug.pdf * The "Ultimate" Anti-Debugging Reference * * https://github.com/LordNoteworthy/al-khaser/wiki/Anti-Debugging-Tricks * Anti Debugging Tricks */ #if !defined(_GNU_SOURCE) && (defined(__linux__) || defined(__unix__) || defined(__posix__)) # define _GNU_SOURCE /* for syscall */ #endif #include <assert.h> #include <stdint.h> #include <stdio.h> #include <string.h> #if defined(_WIN32) || defined(WIN32) || defined(_WIN64) || defined(WIN64) # define IS_WINDOWS 1 # include <windows.h> #endif #if defined(__linux__) || defined(__unix__) || defined(__posix__) # define IS_POSIX 1 # include <errno.h> # include <sys/ptrace.h> # include <sys/syscall.h> # include <unistd.h> #endif #ifndef IS_WINDOWS # define IS_WINDOWS 0 #endif #ifndef IS_POSIX # define IS_POSIX 0 #endif /** * Example of simple function which is protected from breakpoints. * Use asm to also mark the function end, after the return statement, so that * all of its instructions can be checked for breakpoints. * * To implement this function for a new architecture, run something like: * echo 'int f(int v){return v^42;}'|gcc -O2 -xc - -S -o /dev/stdout */ int sensitive_computation(int value); extern uint8_t sensitive_start[]; extern uint8_t sensitive_end[]; __asm__ ( " .text\n" /* Define symbols both with and without underscore prefix to match the C name */ " .globl sensitive_start\n" " .globl _sensitive_start\n" " .globl sensitive_computation\n" " .globl _sensitive_computation\n" " .globl sensitive_end\n" " .globl _sensitive_end\n" "sensitive_start:\n" "_sensitive_start:\n" #if defined(__x86_64__) || defined(__i386__) " .align 16, 0x90\n" "sensitive_computation:\n" "_sensitive_computation:\n" # if defined(__x86_64__) && IS_POSIX " movl %edi, %eax\n" /* First parameter is rdi */ # elif defined(__x86_64__) && IS_WINDOWS " movl %ecx, %eax\n" /* AMD64 Windows stdcall: first parameter is rcx */ # elif defined(__i386__) " movl 4(%esp), %eax\n" /* First parameter is on the stack */ # endif " xorl $42, %eax\n" /* Return value is eax */ " ret\n" #elif defined(__aarch64__) " .align 2\n" "sensitive_computation:\n" "_sensitive_computation:\n" " mov x1, #42\n" " eor x0, x0, x1\n" /* First parameter and return value are x0 */ " ret\n" #elif defined(__arm__) " .align 2\n" "sensitive_computation:\n" "_sensitive_computation:\n" " eor r0, r0, #42\n" /* First parameter and return value are r0 */ " bx lr\n" #else # error "Unknown target architecture" #endif "sensitive_end:\n" "_sensitive_end:\n" ); /** * Return values: * * 0: everything went fine, the program is not being debugged. * * 1: something went wrong, an error occurred. * * 2: the program is being lightly debugged/traced. * * 3: all anti-debug tests were triggered (useful for testing purposes). */ int main(void) { int is_debugged = 0, is_all_triggered = 1; uint8_t *pcode; #if defined(__arm__) /* ARM breakpoint is an undefined instruction. * See BREAKINST_ARM and BREAKINST_THUMB macros in * https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/tree/arch/arm/kernel/ptrace.c * Use integers instead of binary strings to use compiler endianness */ const uint32_t arm_break = 0xe7f001f0; const uint16_t thumb_break = 0xde01; const uint16_t thumb2_break[2] = { 0xf7f0, 0xa000 }; #endif #if IS_WINDOWS HMODULE hKernel32, hNtDll; BOOL (WINAPI *pfnIsDebuggerPresent)(VOID); LONG (WINAPI *pfnNtQueryInformationProcess)(HANDLE, int, PVOID, ULONG, PULONG); const BYTE *pPeb = NULL; BOOL bDebuggerPresent = TRUE; LONG status; DWORD_PTR dwpDebuggerPresent = 1; HANDLE hDebuggerObject = NULL; DWORD dwDebugFlags = 0; #endif /* Check the sensitive function for breakpoints */ assert(sensitive_start < sensitive_end); for (pcode = sensitive_start; pcode < sensitive_end; pcode++) { #if defined(__x86_64__) || defined(__i386__) if (*pcode == 0xcc) { printf("[-] int3 instruction detected at %p\n", (void *)pcode); is_debugged = 1; break; } if (pcode + 1 < sensitive_end && *pcode == 0xcd && *(pcode + 1) == 0x03) { printf("[-] int 3 instruction detected at %p\n", (void *)pcode); is_debugged = 1; break; } #elif defined(__aarch64__) if (!((uintptr_t)pcode & 3) && pcode[3] == 0xd4 && (pcode[2] & 0xe0) == 0x20) { printf("[-] ARM64 brk instruction detected at %p\n", (void *)pcode); is_debugged = 1; break; } #elif defined(__arm__) if (!((uintptr_t)pcode & 3) && !memcmp(pcode, &arm_break, 4)) { printf("[-] ARM break instruction detected at %p\n", (void *)pcode); is_debugged = 1; break; } if (!((uintptr_t)pcode & 1) && !memcmp(pcode, &thumb_break, 2)) { printf("[-] Thumb break instruction detected at %p\n", (void *)pcode); is_debugged = 1; break; } if (!((uintptr_t)pcode & 3) && !memcmp(pcode, &thumb2_break, 4)) { printf("[-] Thumb2 break instruction detected at %p\n", (void *)pcode); is_debugged = 1; break; } #else # warning "Unknown breakpoints for target architecture" #endif } if (pcode == sensitive_end) { if (sensitive_computation(260) == 302) { printf("[+] sensitive_computation looks fine.\n"); is_all_triggered = 0; } else { fprintf(stderr, "[!] sensitive_computation gave an unexpected result.\n"); return 1; } } #if IS_POSIX /* Use ptrace syscall to detect tracers * Don't use ptrace(PTRACE_TRACEME, 0, NULL, NULL) as this could be overridden. */ if (syscall(__NR_ptrace, PTRACE_TRACEME, 0, NULL, NULL) == -1) { if (errno == EPERM) { printf("[-] ptrace(TRACEME) failed. Someone is tracing us.\n"); is_debugged = 1; } else { perror("[!] ptrace(TRACEME)"); return 1; } } else if (syscall(__NR_ptrace, PTRACE_TRACEME, 0, NULL, NULL) == 0) { /* As this test can still be avoided with seccomp filters, or more * simply with gdb "catch syscall ptrace", test a second time. */ printf("[-] ptrace(TRACEME) succeeded two times. I don't buy it.\n"); is_debugged = 1; } else if (errno != EPERM) { perror("[!] ptrace(TRACEME)"); return 1; } else { printf("[+] ptrace(TRACEME) ok.\n"); is_all_triggered = 0; } #endif #if IS_WINDOWS /* Use Windows API, if available */ hKernel32 = GetModuleHandleW(L"kernel32.dll"); pfnIsDebuggerPresent = (BOOL (WINAPI *)(VOID))(void *)GetProcAddress(hKernel32, "IsDebuggerPresent"); if (!pfnIsDebuggerPresent) { printf("[ ] Kernel32!IsDebuggerPresent does not exist.\n"); } else if (pfnIsDebuggerPresent()) { printf("[-] IsDebuggerPresent said there is a debugger.\n"); is_debugged = 1; } else { printf("[+] IsDebuggerPresent returned false.\n"); is_all_triggered = 0; } /* Read the BeingDebugged field of the process environment block. * It is a byte at offset 2. */ # if defined(__x86_64__) __asm__ ("movq %%gs:96, %0" : "=r" (pPeb)); # elif defined(__i386__) __asm__ ("movl %%fs:48, %0" : "=r" (pPeb)); # else # warning "Unknown way to get the PEB on this architecture" # endif if (!pPeb) { printf("[ ] Unable to get the PEB.\n"); } else if (pPeb[2]) { printf("[-] PEB!BeingDebugged is %u.\n", pPeb[2]); is_debugged = 1; } else { printf("[+] PEB!BeingDebugged is false.\n"); is_all_triggered = 0; } /* Use CheckRemoteDebuggerPresent, which uses NtQueryInformationProcess */ if (!CheckRemoteDebuggerPresent(GetCurrentProcess(), &bDebuggerPresent)) { fprintf(stderr, "[!] CheckRemoteDebuggerPresent failed with error %lu.\n", GetLastError()); return 1; } else if (bDebuggerPresent) { printf("[-] CheckRemoteDebuggerPresent is true.\n"); is_debugged = 1; } else { printf("[+] CheckRemoteDebuggerPresent is false.\n"); is_all_triggered = 0; } /* Use NtQueryInformationProcess directly, with class 7 for ProcessDebugPort */ hNtDll = GetModuleHandleW(L"ntdll.dll"); pfnNtQueryInformationProcess = (LONG (WINAPI *)(HANDLE, int, PVOID, ULONG, PULONG)) (void *)GetProcAddress(hNtDll, "NtQueryInformationProcess"); if (!pfnNtQueryInformationProcess) { printf("[ ] ntdll!NtQueryInformationProcess does not exist.\n"); } else { /* Use ProcessDebugPort = 7 */ status = pfnNtQueryInformationProcess(GetCurrentProcess(), 7, &dwpDebuggerPresent, sizeof(dwpDebuggerPresent), NULL); if (status) { fprintf(stderr, "[!] NtQueryInformationProcess(ProcessDebugPort) failed with error %lu.\n", GetLastError()); return 1; } else if (dwpDebuggerPresent) { printf("[-] NtQueryInformationProcess(ProcessDebugPort) returned true.\n"); is_debugged = 1; } else { printf("[+] NtQueryInformationProcess(ProcessDebugPort) returned false.\n"); is_all_triggered = 0; } /* Use ProcessDebugObjectHandle = 30 */ status = pfnNtQueryInformationProcess(GetCurrentProcess(), 30, &hDebuggerObject, sizeof(hDebuggerObject), NULL); if ((ULONG)status == 0xc0000353U) { /* STATUS_PORT_NOT_SET */ printf("[+] NtQueryInformationProcess(ProcessDebugObjectHandle) returned STATUS_PORT_NOT_SET.\n"); is_all_triggered = 0; } else if (status) { fprintf(stderr, "[!] NtQueryInformationProcess(ProcessDebugObjectHandle) failed with error %#lx.\n", status); return 1; } else if (hDebuggerObject) { printf("[-] NtQueryInformationProcess(ProcessDebugObjectHandle) returned %p.\n", hDebuggerObject); is_debugged = 1; } else { printf("[+] NtQueryInformationProcess(ProcessDebugObjectHandle) returned NULL.\n"); is_all_triggered = 0; } /* Use ProcessDebugFlags = 31 */ status = pfnNtQueryInformationProcess(GetCurrentProcess(), 31, &dwDebugFlags, sizeof(dwDebugFlags), NULL); if (status) { fprintf(stderr, "[!] NtQueryInformationProcess(ProcessDebugFlags) failed with error %#lx.\n", status); return 1; } else if (dwDebugFlags != 1) { printf("[-] NtQueryInformationProcess(ProcessDebugFlags) returned %#lx.\n", dwDebugFlags); is_debugged = 1; } else { printf("[+] NtQueryInformationProcess(ProcessDebugFlags) returned %#lx == 1.\n", dwDebugFlags); is_all_triggered = 0; } } #endif return is_debugged ? (2 + is_all_triggered) : 0; }
the_stack_data/153173.c
/* URI Online Judge | 1478 Square Matrix II By Josué Pereira de Castro, Unioeste Brazil https://www.urionlinejudge.com.br/judge/en/problems/view/1478 Timelimit: 1 Write a program that read an integer number N (0 ≤ N ≤ 100) that correspont to the order of a Bidimentional array of integers, and build the Array according to the above example. Input The input consists of several integers numbers, one per line, corresponding to orders from arrays to be built. The end of input is indicated by zero (0). Output For each integer number of input, print the corresponding array according to the example. (the values ​​of the arrays must be formatted in a field of size 3 right justified and separated by a space. None space must be printed after the last character of each row of the array. A blank line must be printed after each array. @author Marcos Lima @profile https://www.urionlinejudge.com.br/judge/pt/profile/242402 @status Accepted @language C (gcc 4.8.5, -O2 -lm) [+0s] @time 0.076s @size 907 Bytes @submission 12/23/19, 12:56:32 AM */ #include <stdio.h> #include <stdlib.h> void gerarMatrixN(unsigned int n) { unsigned int i,j, dec; int **mat; mat = (int **)malloc(n * sizeof(int*)); for(i = 0; i < n; i++) mat[i] = (int *)malloc(n * sizeof(int)); for (i = 0; i < n; i++) { dec = i+1; for(j = 0; j < n; j++,dec--) mat[i][j] = dec; } for (i = 0; i < n; i++) for(j = 0; j < n; j++) mat[i][j] = mat[j][i]; for (i = 0; i < n; i++) { for (j = 0; j < n-1; j++) printf("%3d ", mat[i][j]); printf("%3d\n", mat[i][j]); } printf("\n"); for(i = 0; i < n; i++) free(mat[i]); free(mat); } int main() { unsigned int n; scanf("%u", &n); while(n) { gerarMatrixN(n); scanf("%u", &n); } return 0; }
the_stack_data/89200805.c
#include <stdio.h> void main (void) { int val; char string[10] = "250"; // arguments to scanf must be pointers hence the & sscanf (string, "%d", &val); printf ("The value in the string is %d\n", val); }
the_stack_data/192330999.c
#include<stdio.h> #define V 4 #define INF 99999 void printSolution(int dist[][V]); void floydWarshall (int graph[][V]) { int dist[V][V], i, j, k; for (i = 0; i < V; i++) for (j = 0; j < V; j++) dist[i][j] = graph[i][j]; for (k = 0; k < V; k++) { for (i = 0; i < V; i++) { for (j = 0; j < V; j++) { if (dist[i][k] + dist[k][j] < dist[i][j]) dist[i][j] = dist[i][k] + dist[k][j]; } } } printSolution(dist); } void printSolution(int dist[][V]) { int i,j; printf ("Following matrix shows the shortest distances" " between every pair of vertices \n"); for (i = 0; i < V; i++) { for (j = 0; j < V; j++) { if (dist[i][j] == INF) printf("%7s", "INF"); else printf ("%7d", dist[i][j]); } printf("\n"); } } int main() { int graph[V][V] = { {0, 5, INF, 10}, {INF, 0, 3, INF}, {INF, INF, 0, 1}, {INF, INF, INF, 0} }; floydWarshall(graph); return 0; }
the_stack_data/34513973.c
struct STy { int X; }; #define CALL bar int bar(int X) { return X * 2; } int bar_new(int X) { #pragma spf metadata replace(bar(X)) return X + X; } int foo(int X) { return bar_new(X); }
the_stack_data/92327997.c
#include <stdio.h> int main(void) { int shadrach = 701; int meshach = 709; int abednego = 719; printf("Shadrach is %d\nMeshach is %d\nAbednego is %d\n", shadrach, meshach, abednego); return(0); }
the_stack_data/45606.c
#include <stdio.h> /* rightrot: przesuń x cyklicznie w prawo o n pozycji */ unsigned rightrot(unsigned x, int n) { int wordlength(void); /* długość słowa maszyny */ int rbit; /* skrajnie prawy bit słowa */ while (n-- > 0) { rbit = (x & 1) << (wordlength() - 1); // biorę najmniej znaczący bit i przesuwam go o na najbardziej znaczącą pozycję x >>= 1; // przesuwam całą liczbę o 1 w prawo, dzięki temu wszystkie bity się przesunęły w prawo, a najbardziej znaczący bit jest równy 0, teraz wystarczy dać ora x |= rbit; } return x; } /* wordlength: oblicz długość słowa maszyny */ int wordlength(void) { int i; unsigned v = (unsigned) ~0; // mamy słowo długości n o wartośći 2^(n-1) i dopóki jej nie wyzerujemy to dodajemy do licznika długości for (i = 1; (v >>= 1) > 0; i++) ; return i; } int main() { unsigned int a = 2; int n; n = 1; printf("dla a = %d rotacja w prawo o n = %d pozycji daje nam wynik = %d\n", a, n, rightrot(a,n)); a = 4; n = 2; printf("dla a = %d rotacja w prawo o n = %d pozycji daje nam wynik = %d\n", a, n, rightrot(a,n)); }
the_stack_data/104827287.c
/* ** EPITECH PROJECT, 2019 ** my_strncmp ** File description: ** display */ int my_strncmp(char const *s1, char const *s2, int n) { return (0); }
the_stack_data/62140.c
#include <unistd.h> int main(int argc, char *argv[]) { int i; i = 0; if (argc != 2) write(1, "z\n", 2); else { while (argv[1][i]) { if (argv[1][i] == 'z') { write(1, "z", 1); break ; } i += 1; } write(1, "\n", 1); } return (0); }
the_stack_data/122016404.c
#include <stdio.h> void inter(int *a, int *b){ int t; t = *a; *a = *b; *b = t; printf("%d %d %d %d\n", a, *a, &a, &(*a)); return; } int main(){ int hola = 9, mundo = 12, *pointer, dos = 9; *pointer = 7; printf("%d\n", pointer); printf("%d %d\n", *pointer, hola+mundo+dos); printf("%d %d %d %d\n", &hola, &mundo, &(*pointer), &dos); inter(&hola, &mundo); return 0; }
the_stack_data/830929.c
#include<stdio.h> int main() { int i,n,p[10]={1,2,3,4,5,6,7,8,9,10},min,k=1,btime=0; int bt[10],temp,j,at[10],wt[10],tt[10],ta=0,sum=0; float wavg=0,tavg=0,tsum=0,wsum=0; printf(" -------Shortest Job First Scheduling ( NP )-------\n"); printf("\nEnter the No. of processes :"); scanf("%d",&n); for(i=0;i<n;i++) { printf("\tEnter the burst time of %d process :",i+1); scanf(" %d",&bt[i]); printf("\tEnter the arrival time of %d process :",i+1); scanf(" %d",&at[i]); } /*Sorting According to Arrival Time*/ for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(at[i]<at[j]) { temp=p[j]; p[j]=p[i]; p[i]=temp; temp=at[j]; at[j]=at[i]; at[i]=temp; temp=bt[j]; bt[j]=bt[i]; bt[i]=temp; } } } /*Arranging the table according to Burst time, Execution time and Arrival Time Arrival time <= Execution time */ for(j=0;j<n;j++) { btime=btime+bt[j]; min=bt[k]; for(i=k;i<n;i++) { if (btime>=at[i] && bt[i]<min) { temp=p[k]; p[k]=p[i]; p[i]=temp; temp=at[k]; at[k]=at[i]; at[i]=temp; temp=bt[k]; bt[k]=bt[i]; bt[i]=temp; } } k++; } wt[0]=0; for(i=1;i<n;i++) { sum=sum+bt[i-1]; wt[i]=sum-at[i]; wsum=wsum+wt[i]; } wavg=(wsum/n); for(i=0;i<n;i++) { ta=ta+bt[i]; tt[i]=ta-at[i]; tsum=tsum+tt[i]; } tavg=(tsum/n); printf("************************"); printf("\n RESULT:-"); printf("\nProcess\t Burst\t Arrival\t Waiting\t Turn-around" ); for(i=0;i<n;i++) { printf("\n p%d\t %d\t %d\t\t %d\t\t\t%d",p[i],bt[i],at[i],wt[i],tt[i]); } printf("\n\nAVERAGE WAITING TIME : %f",wavg); printf("\nAVERAGE TURN AROUND TIME : %f",tavg); return 0; }
the_stack_data/115765026.c
/* Generated by CIL v. 1.7.0 */ /* print_CIL_Input is false */ struct _IO_FILE; struct timeval; extern float strtof(char const *str , char const *endptr ) ; extern void signal(int sig , void *func ) ; typedef struct _IO_FILE FILE; extern int atoi(char const *s ) ; extern double strtod(char const *str , char const *endptr ) ; extern int fclose(void *stream ) ; extern void *fopen(char const *filename , char const *mode ) ; extern void abort() ; extern void exit(int status ) ; extern int raise(int sig ) ; extern int fprintf(struct _IO_FILE *stream , char const *format , ...) ; extern int strcmp(char const *a , char const *b ) ; extern int rand() ; extern unsigned long strtoul(char const *str , char const *endptr , int base ) ; void RandomFunc(unsigned int input[1] , unsigned int output[1] ) ; extern int strncmp(char const *s1 , char const *s2 , unsigned long maxlen ) ; extern int gettimeofday(struct timeval *tv , void *tz , ...) ; extern int printf(char const *format , ...) ; int main(int argc , char *argv[] ) ; void megaInit(void) ; extern unsigned long strlen(char const *s ) ; extern long strtol(char const *str , char const *endptr , int base ) ; extern unsigned long strnlen(char const *s , unsigned long maxlen ) ; extern void *memcpy(void *s1 , void const *s2 , unsigned long size ) ; struct timeval { long tv_sec ; long tv_usec ; }; extern void *malloc(unsigned long size ) ; extern int scanf(char const *format , ...) ; void megaInit(void) { { } } void RandomFunc(unsigned int input[1] , unsigned int output[1] ) { unsigned int state[1] ; unsigned short copy11 ; unsigned short copy12 ; { state[0UL] = (input[0UL] + 914778474UL) * 2674260758U; if (state[0UL] & 1U) { if (state[0UL] & 1U) { if (state[0UL] & 1U) { state[0UL] += state[0UL]; } else { state[0UL] += state[0UL]; } } else if ((state[0UL] >> 2U) & 1U) { state[0UL] *= state[0UL]; } else { copy11 = *((unsigned short *)(& state[0UL]) + 0); *((unsigned short *)(& state[0UL]) + 0) = *((unsigned short *)(& state[0UL]) + 1); *((unsigned short *)(& state[0UL]) + 1) = copy11; } } else if (state[0UL] & 1U) { state[0UL] += state[0UL]; } else { copy12 = *((unsigned short *)(& state[0UL]) + 1); *((unsigned short *)(& state[0UL]) + 1) = *((unsigned short *)(& state[0UL]) + 0); *((unsigned short *)(& state[0UL]) + 0) = copy12; } output[0UL] = state[0UL] - 46733160U; } } int main(int argc , char *argv[] ) { unsigned int input[1] ; unsigned int output[1] ; int randomFuns_i5 ; unsigned int randomFuns_value6 ; int randomFuns_main_i7 ; { megaInit(); if (argc != 2) { printf("Call this program with %i arguments\n", 1); exit(-1); } else { } randomFuns_i5 = 0; while (randomFuns_i5 < 1) { randomFuns_value6 = (unsigned int )strtoul(argv[randomFuns_i5 + 1], 0, 10); input[randomFuns_i5] = randomFuns_value6; randomFuns_i5 ++; } RandomFunc(input, output); if (output[0] == 37317403U) { printf("You win!\n"); } else { } randomFuns_main_i7 = 0; while (randomFuns_main_i7 < 1) { printf("%u\n", output[randomFuns_main_i7]); randomFuns_main_i7 ++; } } }
the_stack_data/82406.c
#include<stdio.h> unsigned long long fact(unsigned long long x) { if(x > 1) return x*fact(x-1); else return 1; } int main(void) { unsigned int n, t, s=0, r; printf("Enter the number: "); scanf("%u", &n); printf("\nFactorial of the number is: %llu",fact(n)); return 0; }
the_stack_data/101068.c
//Algoritimo de calculo de media do semestre para 3 provas para 5 alunos #include <stdio.h> #include <stdlib.h> int main() { system("cls"); float aluno1 = 0, aluno2 = 0, aluno3 = 0, aluno4 = 0, aluno5 = 0, p1, p2, p3, media; int contagem = 0, raaluno = 0; for (contagem = 1; contagem <= 5; contagem++) { raaluno = raaluno + 1; printf("\n\n Aluno N%i Nota P1:", raaluno); scanf("%f", &p1); printf("\n\n Aluno N%i Nota P2:", raaluno); scanf("%f", &p2); printf("\n\n Aluno N%i Nota P3:", raaluno); scanf("%f", &p3); media = (p1 + p2 + p3) / 3; if (contagem == 1) { aluno1 = media; } if (contagem == 2) { aluno2 = media; } if (contagem == 3) { aluno3 = media; } if (contagem == 4) { aluno4 = media; } if (contagem == 5) { aluno5 = media; } } printf("\n\n---RESULTADO---"); printf("\n\nAluno 1 Media:%0.2f", aluno1); printf("\n\nAluno 2 Media:%0.2f", aluno2); printf("\n\nAluno 3 Media:%0.2f", aluno3); printf("\n\nAluno 4 Media:%0.2f", aluno4); printf("\n\nAluno 5 Media:%0.2f", aluno5); return 0; }
the_stack_data/686867.c
/* Program to print the TWin Prime numbers upto a range (twin prime means if the difference of two prime number is 2 Example: 3-5, 5-7, 11-13, 17-19 etc. SUMIT KUMAR */ #include<stdio.h> int main(void) { int n,j,i,flag,p=0; int a[100]; printf("\n Enter the value of N: "); scanf("%d",&n); for(i=2;i<=n;i++) { flag=0; for(j=2;j<=i/2;j++) { if(i%j==0) { flag=1; break; } } /* end of jth loop */ if(flag==0) a[p++]=i; } /* end of ith loop */ for(j=0;j<=p-1;j++); /* check for twin prime */ { if(a[j+1]-a[j]==2) { printf("\m\t The %d And %d are Twin Prime numbers " ,a[j],a[j+1]); } } return 0; }
the_stack_data/1210550.c
// RUN: %clang_cc1 -triple wasm32-unknown-unknown -O3 -emit-llvm -o - %s \ // RUN: | FileCheck %s -check-prefix=WEBASSEMBLY32 // RUN: %clang_cc1 -triple wasm64-unknown-unknown -O3 -emit-llvm -o - %s \ // RUN: | FileCheck %s -check-prefix=WEBASSEMBLY64 __SIZE_TYPE__ f1(void) { return __builtin_wasm_memory_size(); // WEBASSEMBLY32: call {{i.*}} @llvm.wasm.memory.size.i32() // WEBASSEMBLY64: call {{i.*}} @llvm.wasm.memory.size.i64() } void f2(long delta) { __builtin_wasm_grow_memory(delta); // WEBASSEMBLY32: call void @llvm.wasm.grow.memory.i32(i32 %{{.*}}) // WEBASSEMBLY64: call void @llvm.wasm.grow.memory.i64(i64 %{{.*}}) }
the_stack_data/720050.c
int minCostClimbingStairs(int* cost, int costSize){ int i; int dp[costSize + 1]; for (i = 0; i < costSize + 1; ++i) { dp[i] = 0; } for (i = 2; i < costSize + 1; ++i) { if (dp[i - 2] + cost[i - 2] < dp[i - 1] + cost[i - 1]) dp[i] = dp[i - 2] + cost[i - 2]; else dp[i] = dp[i - 1] + cost[i - 1]; } return dp[costSize]; }
the_stack_data/190769372.c
/* $Id: gld_debug_clip.c,v 1.1 2004/04/20 11:13:11 alanh Exp $ */ /* * Mesa 3-D graphics library * Version: 3.5 * * Copyright (C) 1999-2001 Brian Paul All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * BRIAN PAUL BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * * Authors: * Gareth Hughes <[email protected]> */ #ifdef DEBUG /* This code only used for debugging */ // Stub to enable Mesa to build. KeithH #pragma message("NOTE: Using gld_debug_clip.c HACK") void _math_test_all_cliptest_functions( char *description ) { } #endif /* DEBUG */
the_stack_data/148579071.c
#include <stdio.h> #define paste(front,back) front ## back int main() { paste(pri,ntf)("helloworld\n"); return 0; }
the_stack_data/80955.c
/* Test __attribute__((gnu_inline)). */ /* { dg-do compile } */ /* { dg-options "-std=c99" } */ /* { dg-final { scan-assembler "func1" } } */ /* { dg-final { scan-assembler-not "func2" } } */ /* { dg-final { scan-assembler "func3" } } */ /* { dg-final { scan-assembler "func4" } } */ #if __STDC_VERSION__ >= 199901L # define inline __attribute__((gnu_inline)) inline #endif extern inline int func1 (void) { return 0; } inline int func1 (void) { return 1; } extern int func2 (void); extern inline int func2 (void) { return 2; } inline int func3 (void); inline int func3 (void) { return 3; } extern int func4 (void); extern inline int func4 (void) { return 4; } int func4 (void) { return 5; }
the_stack_data/73576586.c
#include <stdio.h> #include <stdlib.h> void input(int a[],int n) { int i=0; for(i=0;i<n;i++) { scanf("%d",&a[i]); } } void merge(int arr[], int l, int m, int r) { int i, j, k; int n1 = m - l + 1; int n2 = r - m; /* create temp arrays */ int L[n1], R[n2]; /* Copy data to temp arrays L[] and R[] */ for (i = 0; i < n1; i++) L[i] = arr[l + i]; for (j = 0; j < n2; j++) R[j] = arr[m + 1 + j]; /* Merge the temp arrays back into arr[l..r]*/ i = 0; j = 0; k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } /* Copy the remaining elements of L[], if there are any */ while (i < n1) { arr[k] = L[i]; i++; k++; } /* Copy the remaining elements of R[], if there are any */ while (j < n2) { arr[k] = R[j]; j++; k++; } } /* l is for left index and r is right index of the sub-array of arr to be sorted */ void mergeSort(int arr[], int l, int r) { if (l < r) { int m = l + (r - l) / 2; mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); } } /* UTILITY FUNCTIONS */ /* Function to print an array */ void printArray(int A[], int size) { int i; for (i = 0; i < size; i++) printf("%d ", A[i]); printf("\n"); } /* Driver program to test above functions */ int main() { int arr[100]; int arr_size; printf("enter size of array:"); scanf("%d",&arr_size); input(arr,arr_size); mergeSort(arr, 0, arr_size - 1); printf("\nSorted array is \n"); printArray(arr, arr_size); return 0; }
the_stack_data/234517771.c
/* This is a prgram to correct this line of code #include <stdio.h>; main[] { /*Program to illustrate errors in a C program. int i, j; float i; j = 40000; PRINTF("The value of i is %d" i); PRINT("Size of an integer is %d", sizeof(int)); ] Author: Daniel Tilley Date: 23/09/2014 */ #include <stdio.h> main() { int j; float i; i=20000; printf("The value of i is %f\n" , i); printf("Size of an integer is %d" , sizeof(int)); getchar(); } //End Main
the_stack_data/145452603.c
/* * Copyright (C) 2011 Peter Zotov <[email protected]> * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file. */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <stdint.h> #ifdef __MINGW32__ #include "mingw.h" #else #include <sys/poll.h> #endif static const char hex[] = "0123456789abcdef"; int gdb_send_packet(int fd, char* data) { int length = strlen(data) + 5; char* packet = malloc(length); /* '$' data (hex) '#' cksum (hex) */ memset(packet, 0, length); packet[0] = '$'; uint8_t cksum = 0; for(unsigned int i = 0; i < strlen(data); i++) { packet[i + 1] = data[i]; cksum += data[i]; } packet[length - 4] = '#'; packet[length - 3] = hex[cksum >> 4]; packet[length - 2] = hex[cksum & 0xf]; while(1) { if(write(fd, packet, length) != length) { free(packet); return -2; } char ack; if(read(fd, &ack, 1) != 1) { free(packet); return -2; } if(ack == '+') { free(packet); return 0; } } } #define ALLOC_STEP 1024 int gdb_recv_packet(int fd, char** buffer) { unsigned packet_size = ALLOC_STEP + 1, packet_idx = 0; uint8_t cksum = 0; char recv_cksum[3] = {0}; char* packet_buffer = malloc(packet_size); unsigned state; start: state = 0; /* * 0: waiting $ * 1: data, waiting # * 2: cksum 1 * 3: cksum 2 * 4: fin */ char c; while(state != 4) { if(read(fd, &c, 1) != 1) { return -2; } switch(state) { case 0: if(c != '$') { // ignore } else { state = 1; } break; case 1: if(c == '#') { state = 2; } else { packet_buffer[packet_idx++] = c; cksum += c; if(packet_idx == packet_size) { packet_size += ALLOC_STEP; packet_buffer = realloc(packet_buffer, packet_size); } } break; case 2: recv_cksum[0] = c; state = 3; break; case 3: recv_cksum[1] = c; state = 4; break; } } uint8_t recv_cksum_int = strtoul(recv_cksum, NULL, 16); if(recv_cksum_int != cksum) { char nack = '-'; if(write(fd, &nack, 1) != 1) { return -2; } goto start; } else { char ack = '+'; if(write(fd, &ack, 1) != 1) { return -2; } } packet_buffer[packet_idx] = 0; *buffer = packet_buffer; return packet_idx; } // Here we skip any characters which are not \x03, GDB interrupt. // As we use the mode with ACK, in a (very unlikely) situation of a packet // lost because of this skipping, it will be resent anyway. int gdb_check_for_interrupt(int fd) { struct pollfd pfd; pfd.fd = fd; pfd.events = POLLIN; if(poll(&pfd, 1, 0) != 0) { char c; if(read(fd, &c, 1) != 1) return -2; if(c == '\x03') // ^C return 1; } return 0; }
the_stack_data/580744.c
#include <stdio.h> #include <stdlib.h> int main() { int *ptr = (int *)malloc(sizeof(int)*2); int i; int *ptr_new; *ptr = 10; *(ptr + 1) = 20; ptr_new = (int *)realloc(ptr, sizeof(int)*3); printf("%d\n", *ptr); *(ptr_new + 2) = 30; for(i = 0; i < 3; i++) printf("%d ", *(ptr_new + i)); return 0; }
the_stack_data/122014957.c
int main() { int x = 0; for (int i = 0; i < 9999, i < 3; i++) x++; return x; }
the_stack_data/16495.c
/*Exercise 4 - Functions Implement the three functions minimum(), maximum() and multiply() below the main() function. Do not change the code given in the main() function when you are implementing your solution.*/ #include <stdio.h> int minimum(int num1, int num2); int maximum(int num1, int num2); int multiply(int num1, int num2); int main() { int no1, no2; printf("Enter a value for no 1 : "); scanf("%d", &no1); printf("Enter a value for no 2 : "); scanf("%d", &no2); printf("%d ", minimum(no1, no2)); printf("%d ", maximum(no1, no2)); printf("%d ", multiply(no1, no2)); return 0; } int minimum(int num1, int num2) { int O; if(num1 < num2) { O = num1; } else { O = num2; } return O; } int maximum(int num1, int num2) { int O; if(num1 > num2) { O = num1; } else { O = num2; } return O; } int multiply(int num1, int num2) { int O; O = num1 * num2; return O; }
the_stack_data/139662.c
/* #include<stdio.h> */ /* To obtain two read effects on a and b and a warning abount * ineffective update of i in call02 */ typedef struct two_fields{int one; int two[10];} tf_t; void call02(int i, int j, int y[10], int * q[10], tf_t *p) { /* i can be modified locally, but it won't show in the summary effects... which creates a problem for transformer and precondition computation. */ i = j + 1; y[i] = 0; p->one = 1; p->two[j] = 2.; *q[i]=3; return; } int main() { int a = 1; int b = 2; int x[10], aa[10], i; int * ap[10]; tf_t s; tf_t *sp = &s; /* Initialization added to avoid a segfault in the callee */ for(i=0;i<10;i++) ap[i] = &aa[i]; call02(a, b, x, ap, sp); return 0; }
the_stack_data/125141849.c
#include <stddef.h> #include <stdio.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <sys/wait.h> #include <setjmp.h> #include <stdbool.h> static char* const ARG_DELIM = " \t\r\a\n"; volatile pid_t child; static sigjmp_buf env; #define INTRECEIVED 42 int my_system(char* const* args) { if (!(child = fork())) { exit(execvp(args[0], args)); } int status; wait(&status); child = -1; return status; } void handler(int code) { if (child != -1) { kill(SIGINT, child); putchar('\n'); } else { siglongjmp(env, INTRECEIVED); } } int main() { struct sigaction sa = {0}; sa.sa_handler = handler; sigaction(SIGINT, &sa, NULL); char* line = NULL; size_t len; while (1) { if (sigsetjmp(env, true) == INTRECEIVED) { putchar('\n'); } printf("$ "); if (getline(&line, &len, stdin) == -1) break; int nargs = 0; char** args = NULL; char* p = strtok(line, ARG_DELIM); if (!p) continue; for (;;) { if (!(args = realloc(args, sizeof(char*) * ++nargs))) abort(); args[nargs - 1] = p; if (!p) break; p = strtok(NULL, ARG_DELIM); } if (!strcmp(args[0], "cd")) { chdir(getenv("HOME")); } else if (!strcmp(args[0], "exit")) { exit(0); } else { if (my_system(args) == -1) { perror(args[0]); } } free(args); } free(line); }
the_stack_data/142326725.c
#include <stdio.h> #include <stdlib.h> int main(){ int a, b, c, largest; scanf("%d %d %d", &a, &b, &c); if(a > b && a > c){ printf("%d", a); }else if(b > a && b > c){ printf("%d", b); }else{ printf("%d", c); } return 0; }
the_stack_data/270445.c
#define LIMIT 10 int a[LIMIT]; void pass_through_array () { for(unsigned i=0; i<LIMIT; i++) a[0] = a[0]; } void main (void) { a[0] = 0; a[1] = 0; pass_through_array(); assert(a[0] == 0 && a[1] == 0); }
the_stack_data/32950391.c
#include <stdio.h> typedef char byte; #define REG8_MASK 0x000000FFU typedef union register_8_bits__ { byte value; struct bits__ { byte b0 : 1; byte b1 : 1; byte b2 : 1; byte b3 : 1; byte b4 : 1; byte b5 : 1; byte b6 : 1; byte b7 : 1; }bits; struct nibbles__ { byte low : 4; byte high : 4; }nibbles; }register_8_bits; int main() { register_8_bits my_reg; my_reg.value = 0x00; // clear register printf("Register value : %X\n", my_reg.value & REG8_MASK); my_reg.bits.b2 = 1; // sets b2 my_reg.bits.b7 = 1; // sets b7 printf("Register value : %X\n", my_reg.value & REG8_MASK); printf("Register value low : %X\n", my_reg.nibbles.low &0xF); printf("Register value high : %X\n", my_reg.nibbles.high &0xF); my_reg.value = 0x00; // for setting bit 2 my_reg.bits.b2 = 1; printf("b2 set, Register value : 0x%X\n", my_reg.value); // for clearing bit 2 my_reg.bits.b2 = 0; printf("b2 cleared, Register value : 0x%X\n", my_reg.value); // for setting b1 my_reg.bits.b1 = 1; printf("b1 set, Register value : 0x%X\n", my_reg.value); // for setting high nibble bits to '1110' my_reg.nibbles.high = 0xE; // 0xE is 1110 in binary printf("nibble high is set to 0xE, Register value : 0x%X\n", my_reg.value & 0xFF); // for setting the entire 8 bits to 0xFF my_reg.value = 0xFF; printf("Value set to 0xFF, Register value : 0x%X\n", my_reg.value & 0xFF); return 0; }
the_stack_data/257303.c
#if __WORDSIZE == 32 #define JIT_INSTR_MAX 64 0, /* data */ 0, /* live */ 0, /* align */ 0, /* save */ 0, /* load */ 0, /* #name */ 0, /* #note */ 0, /* label */ 64, /* prolog */ 0, /* ellipsis */ 0, /* va_push */ 0, /* allocai */ 0, /* allocar */ 0, /* arg */ 0, /* getarg_c */ 0, /* getarg_uc */ 0, /* getarg_s */ 0, /* getarg_us */ 0, /* getarg_i */ 0, /* getarg_ui */ 0, /* getarg_l */ 0, /* putargr */ 0, /* putargi */ 0, /* va_start */ 0, /* va_arg */ 0, /* va_arg_d */ 0, /* va_end */ 4, /* addr */ 12, /* addi */ 4, /* addcr */ 12, /* addci */ 4, /* addxr */ 8, /* addxi */ 4, /* subr */ 12, /* subi */ 4, /* subcr */ 12, /* subci */ 4, /* subxr */ 8, /* subxi */ 16, /* rsbi */ 28, /* mulr */ 36, /* muli */ 40, /* qmulr */ 44, /* qmuli */ 32, /* qmulr_u */ 40, /* qmuli_u */ 36, /* divr */ 40, /* divi */ 36, /* divr_u */ 40, /* divi_u */ 40, /* qdivr */ 40, /* qdivi */ 40, /* qdivr_u */ 40, /* qdivi_u */ 36, /* remr */ 40, /* remi */ 36, /* remr_u */ 40, /* remi_u */ 4, /* andr */ 12, /* andi */ 4, /* orr */ 12, /* ori */ 4, /* xorr */ 12, /* xori */ 12, /* lshr */ 4, /* lshi */ 12, /* rshr */ 4, /* rshi */ 12, /* rshr_u */ 4, /* rshi_u */ 4, /* negr */ 4, /* comr */ 8, /* ltr */ 8, /* lti */ 8, /* ltr_u */ 8, /* lti_u */ 8, /* ler */ 8, /* lei */ 8, /* ler_u */ 8, /* lei_u */ 8, /* eqr */ 12, /* eqi */ 8, /* ger */ 8, /* gei */ 8, /* ger_u */ 8, /* gei_u */ 8, /* gtr */ 8, /* gti */ 8, /* gtr_u */ 8, /* gti_u */ 8, /* ner */ 8, /* nei */ 4, /* movr */ 8, /* movi */ 4, /* extr_c */ 4, /* extr_uc */ 4, /* extr_s */ 4, /* extr_us */ 0, /* extr_i */ 0, /* extr_ui */ 4, /* htonr_us */ 4, /* htonr_ui */ 0, /* htonr_l */ 8, /* ldr_c */ 12, /* ldi_c */ 4, /* ldr_uc */ 8, /* ldi_uc */ 8, /* ldr_s */ 12, /* ldi_s */ 4, /* ldr_us */ 8, /* ldi_us */ 4, /* ldr_i */ 8, /* ldi_i */ 0, /* ldr_ui */ 0, /* ldi_ui */ 0, /* ldr_l */ 0, /* ldi_l */ 8, /* ldxr_c */ 8, /* ldxi_c */ 4, /* ldxr_uc */ 4, /* ldxi_uc */ 8, /* ldxr_s */ 8, /* ldxi_s */ 4, /* ldxr_us */ 4, /* ldxi_us */ 4, /* ldxr_i */ 4, /* ldxi_i */ 0, /* ldxr_ui */ 0, /* ldxi_ui */ 0, /* ldxr_l */ 0, /* ldxi_l */ 4, /* str_c */ 8, /* sti_c */ 4, /* str_s */ 8, /* sti_s */ 4, /* str_i */ 8, /* sti_i */ 0, /* str_l */ 0, /* sti_l */ 8, /* stxr_c */ 4, /* stxi_c */ 8, /* stxr_s */ 4, /* stxi_s */ 8, /* stxr_i */ 4, /* stxi_i */ 0, /* stxr_l */ 0, /* stxi_l */ 8, /* bltr */ 8, /* blti */ 8, /* bltr_u */ 8, /* blti_u */ 8, /* bler */ 12, /* blei */ 8, /* bler_u */ 8, /* blei_u */ 8, /* beqr */ 16, /* beqi */ 8, /* bger */ 8, /* bgei */ 8, /* bger_u */ 8, /* bgei_u */ 8, /* bgtr */ 8, /* bgti */ 8, /* bgtr_u */ 8, /* bgti_u */ 8, /* bner */ 16, /* bnei */ 12, /* bmsr */ 16, /* bmsi */ 12, /* bmcr */ 16, /* bmci */ 8, /* boaddr */ 8, /* boaddi */ 8, /* boaddr_u */ 8, /* boaddi_u */ 8, /* bxaddr */ 8, /* bxaddi */ 8, /* bxaddr_u */ 8, /* bxaddi_u */ 12, /* bosubr */ 16, /* bosubi */ 16, /* bosubr_u */ 20, /* bosubi_u */ 12, /* bxsubr */ 16, /* bxsubi */ 16, /* bxsubr_u */ 20, /* bxsubi_u */ 0, /* jmpr */ 12, /* jmpi */ 40, /* callr */ 44, /* calli */ 0, /* prepare */ 0, /* pushargr */ 0, /* pushargi */ 0, /* finishr */ 0, /* finishi */ 0, /* ret */ 0, /* retr */ 0, /* reti */ 0, /* retval_c */ 0, /* retval_uc */ 0, /* retval_s */ 0, /* retval_us */ 0, /* retval_i */ 0, /* retval_ui */ 0, /* retval_l */ 64, /* epilog */ 0, /* arg_f */ 0, /* getarg_f */ 0, /* putargr_f */ 0, /* putargi_f */ 4, /* addr_f */ 16, /* addi_f */ 4, /* subr_f */ 16, /* subi_f */ 16, /* rsbi_f */ 4, /* mulr_f */ 16, /* muli_f */ 4, /* divr_f */ 16, /* divi_f */ 4, /* negr_f */ 4, /* absr_f */ 4, /* sqrtr_f */ 16, /* ltr_f */ 28, /* lti_f */ 16, /* ler_f */ 28, /* lei_f */ 16, /* eqr_f */ 28, /* eqi_f */ 16, /* ger_f */ 28, /* gei_f */ 16, /* gtr_f */ 28, /* gti_f */ 16, /* ner_f */ 28, /* nei_f */ 16, /* unltr_f */ 28, /* unlti_f */ 16, /* unler_f */ 28, /* unlei_f */ 16, /* uneqr_f */ 28, /* uneqi_f */ 16, /* unger_f */ 28, /* ungei_f */ 16, /* ungtr_f */ 28, /* ungti_f */ 16, /* ltgtr_f */ 28, /* ltgti_f */ 16, /* ordr_f */ 28, /* ordi_f */ 16, /* unordr_f */ 28, /* unordi_f */ 12, /* truncr_f_i */ 0, /* truncr_f_l */ 12, /* extr_f */ 4, /* extr_d_f */ 4, /* movr_f */ 12, /* movi_f */ 4, /* ldr_f */ 12, /* ldi_f */ 4, /* ldxr_f */ 4, /* ldxi_f */ 4, /* str_f */ 12, /* sti_f */ 8, /* stxr_f */ 4, /* stxi_f */ 16, /* bltr_f */ 28, /* blti_f */ 16, /* bler_f */ 28, /* blei_f */ 16, /* beqr_f */ 28, /* beqi_f */ 16, /* bger_f */ 28, /* bgei_f */ 16, /* bgtr_f */ 28, /* bgti_f */ 16, /* bner_f */ 28, /* bnei_f */ 16, /* bunltr_f */ 28, /* bunlti_f */ 16, /* bunler_f */ 28, /* bunlei_f */ 16, /* buneqr_f */ 28, /* buneqi_f */ 16, /* bunger_f */ 28, /* bungei_f */ 16, /* bungtr_f */ 28, /* bungti_f */ 16, /* bltgtr_f */ 28, /* bltgti_f */ 16, /* bordr_f */ 28, /* bordi_f */ 16, /* bunordr_f */ 28, /* bunordi_f */ 0, /* pushargr_f */ 0, /* pushargi_f */ 0, /* retr_f */ 0, /* reti_f */ 0, /* retval_f */ 0, /* arg_d */ 0, /* getarg_d */ 0, /* putargr_d */ 0, /* putargi_d */ 4, /* addr_d */ 24, /* addi_d */ 4, /* subr_d */ 24, /* subi_d */ 24, /* rsbi_d */ 4, /* mulr_d */ 24, /* muli_d */ 4, /* divr_d */ 24, /* divi_d */ 4, /* negr_d */ 4, /* absr_d */ 4, /* sqrtr_d */ 16, /* ltr_d */ 36, /* lti_d */ 16, /* ler_d */ 36, /* lei_d */ 16, /* eqr_d */ 36, /* eqi_d */ 16, /* ger_d */ 36, /* gei_d */ 16, /* gtr_d */ 36, /* gti_d */ 16, /* ner_d */ 36, /* nei_d */ 16, /* unltr_d */ 36, /* unlti_d */ 16, /* unler_d */ 36, /* unlei_d */ 16, /* uneqr_d */ 36, /* uneqi_d */ 16, /* unger_d */ 36, /* ungei_d */ 16, /* ungtr_d */ 36, /* ungti_d */ 16, /* ltgtr_d */ 36, /* ltgti_d */ 16, /* ordr_d */ 36, /* ordi_d */ 16, /* unordr_d */ 36, /* unordi_d */ 12, /* truncr_d_i */ 0, /* truncr_d_l */ 12, /* extr_d */ 4, /* extr_f_d */ 4, /* movr_d */ 20, /* movi_d */ 4, /* ldr_d */ 12, /* ldi_d */ 4, /* ldxr_d */ 4, /* ldxi_d */ 4, /* str_d */ 12, /* sti_d */ 8, /* stxr_d */ 4, /* stxi_d */ 16, /* bltr_d */ 36, /* blti_d */ 16, /* bler_d */ 36, /* blei_d */ 16, /* beqr_d */ 36, /* beqi_d */ 16, /* bger_d */ 36, /* bgei_d */ 16, /* bgtr_d */ 36, /* bgti_d */ 16, /* bner_d */ 36, /* bnei_d */ 16, /* bunltr_d */ 36, /* bunlti_d */ 16, /* bunler_d */ 36, /* bunlei_d */ 16, /* buneqr_d */ 36, /* buneqi_d */ 16, /* bunger_d */ 36, /* bungei_d */ 16, /* bungtr_d */ 36, /* bungti_d */ 16, /* bltgtr_d */ 36, /* bltgti_d */ 16, /* bordr_d */ 36, /* bordi_d */ 16, /* bunordr_d */ 36, /* bunordi_d */ 0, /* pushargr_d */ 0, /* pushargi_d */ 0, /* retr_d */ 0, /* reti_d */ 0, /* retval_d */ 0, /* movr_w_f */ 0, /* movr_ww_d */ 0, /* movr_w_d */ 0, /* movr_f_w */ 0, /* movi_f_w */ 0, /* movr_d_ww */ 0, /* movi_d_ww */ 0, /* movr_d_w */ 0, /* movi_d_w */ #endif /* __WORDSIZE */
the_stack_data/862832.c
#include <stdio.h> #include <stdbool.h> #define LENGTH 100 static bool BinarySearch(int arr[], int length, int target); static bool RecursionSearch(int arr[], int start, int end, int target); int main(int argc, char *argv[]) { int list[LENGTH]; int index = 0; int target = atoi(argv[1]); while (index < LENGTH) { list[index] = index * 2; index++; } printf("The %d %s in array.\n", target, BinarySearch(list, LENGTH, target) ? "is" : "is not"); return 0; } static bool BinarySearch(int arr[], int length, int target) { return RecursionSearch(arr, 0, length - 1, target); } static bool RecursionSearch(int arr[], int start, int end, int target) { int middle_index = (start + end) / 2; int middle_value = arr[middle_index]; if(end - start ==1) return target == arr[end] || target == arr[start]; if (target < middle_value) { return RecursionSearch(arr, start, middle_index, target); } else if (target > middle_value) { return RecursionSearch(arr, middle_index, end, target); } else if (target == middle_value) { return true; } }
the_stack_data/1896.c
#include <stdio.h> #include <stdlib.h> int main() { printf("hello world\n"); return 0; }
the_stack_data/59991.c
#include <stdio.h> int main(){ int i=1, j=60; while(j>=0){ printf("I=%d ", i); i+=3; printf("J=%d\n", j); j-=5; } return 0; }
the_stack_data/32951019.c
#include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> /* - bekérünk egy sztringet - készítsünk erről egy másolatot, amit lássunk el nagy kezdőbetűvel - pl.: anna Anna */ int main() { char *s = "anna"; char *t = malloc(strlen(s) + 1); strcpy(t, s); t[0] = toupper(t[0]); printf("%s\n", s); printf("%s\n", t); free(t); return 0; }
the_stack_data/12638131.c
#include <stdio.h> #include <string.h> int main(){ char ch='a'; char a[100]=""; printf("%d\n",strlen(a)); }
the_stack_data/153038.c
#ifdef TEST_MODE_ENABLED void kill_qemu(void); void kill_qemu(void) { while(1) { __asm__ __volatile__("outw %w0, %w1" : : "ax" (0x2000), "Nd" (0x604)); __asm__ ("hlt"); } } #endif
the_stack_data/34513838.c
static const unsigned char unfold_ico_data[] = { 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x20, 0x20, 0x10, 0x00, 0x01, 0x00, 0x04, 0x00, 0xe8, 0x02, 0x00, 0x00, 0x26, 0x00, 0x00, 0x00, 0x10, 0x10, 0x10, 0x00, 0x01, 0x00, 0x04, 0x00, 0x28, 0x01, 0x00, 0x00, 0x0e, 0x03, 0x00, 0x00, 0x28, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x80, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x80, 0x00, 0x00, 0x80, 0x80, 0x80, 0x00, 0xc0, 0xc0, 0xc0, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xfe, 0x7f, 0xff, 0xff, 0xfc, 0x3f, 0xff, 0xff, 0xf8, 0x1f, 0xff, 0xff, 0xf0, 0x0f, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xc0, 0x03, 0xff, 0xff, 0x80, 0x01, 0xff, 0xff, 0x00, 0x00, 0xff, 0xfe, 0x00, 0x00, 0x7f, 0xfc, 0x00, 0x00, 0x3f, 0xf8, 0x00, 0x00, 0x1f, 0xf0, 0x00, 0x00, 0x0f, 0xe0, 0x00, 0x00, 0x07, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xe0, 0x07, 0xff, 0xff, 0xe0, 0x07, 0xff, 0x28, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x80, 0x00, 0x80, 0x00, 0x00, 0x00, 0x80, 0x00, 0x80, 0x00, 0x80, 0x80, 0x00, 0x00, 0xc0, 0xc0, 0xc0, 0x00, 0x80, 0x80, 0x80, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xf0, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x7f, 0x00, 0x00, 0xfc, 0x3f, 0x00, 0x00, 0xf8, 0x1f, 0x00, 0x00, 0xf0, 0x0f, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0xc0, 0x03, 0x00, 0x00, 0x80, 0x01, 0x00, 0x00, 0xf8, 0x1f, 0x00, 0x00, 0xf8, 0x1f, 0x00, 0x00, 0xf8, 0x1f, 0x00, 0x00, 0xf8, 0x1f, 0x00, 0x00, 0xf8, 0x1f, 0x00, 0x00, 0xf8, 0x1f, 0x00, 0x00, 0xf8, 0x1f, 0x00, 0x00, 0xf8, 0x1f, 0x00, 0x00, 0xf8, 0x1f, 0x00, 0x00 };
the_stack_data/1183823.c
#include <stdio.h> /** * 计算1Byte CRC8(字符,前一字符计算出的 CRC) */ unsigned char crc8FormByte(unsigned char in, unsigned char prev_crc) { unsigned char i, crc; crc = prev_crc; for(i = 0; i < 8; i++) { if(((in & 0x01) ^ (crc & 0x01)) == 0) { crc >>= 1; } /* 做(1),(2); (1)=0,则CRC向高位移1位. */ else { crc = crc ^ 0x18; /* (1)=1,则异或18 */ crc >>= 1; crc |= 0x80; /* 置CRC.0为1 */ } in >>= 1; } return crc; } ///计算指定数据的 CRC8(字符串,起始位置,字符串长度) unsigned char crc8FormBytes(unsigned char *in, unsigned char loc, unsigned char len) { unsigned char CRC=0x00; for (int i=loc; i<len+loc; i++) { CRC = crc8FormByte(in[i], CRC); // Serial.println(in[i], HEX); } return CRC; } ///翻转字节顺序 (8-bit) unsigned char reverse8( unsigned char c ) { c = ( c & 0x55 ) << 1 | ( c & 0xAA ) >> 1; c = ( c & 0x33 ) << 2 | ( c & 0xCC ) >> 2; c = ( c & 0x0F ) << 4 | ( c & 0xF0 ) >> 4; return c; } ///翻转字节顺序 (16-bit) unsigned short ReverseBytes16(unsigned short value) { return (unsigned short)((value & 0xFF) << 8 | (value & 0xFF00) >> 8); } ///翻转字节顺序 (32-bit) unsigned long ReverseBytes32(unsigned long value) { return (value & 0x000000FFU) << 24 | (value & 0x0000FF00U) << 8 | (value & 0x00FF0000U) >> 8 | (value & 0xFF000000U) >> 24; } ///翻转字节顺序 (64-bit) unsigned long long ReverseBytes64(unsigned long long value) { return (value & 0x00000000000000FFUL) << 56 | (value & 0x000000000000FF00UL) << 40 | (value & 0x0000000000FF0000UL) << 24 | (value & 0x00000000FF000000UL) << 8 | (value & 0x000000FF00000000UL) >> 8 | (value & 0x0000FF0000000000UL) >> 24 | (value & 0x00FF000000000000UL) >> 40 | (value & 0xFF00000000000000UL) >> 56; } int main(int argc, char const *argv[]) { unsigned char oldCRC = 0x00; unsigned char crc = 0x00; unsigned char data[3] = {0x11, 0x10, 0xAA}; unsigned char data2[8] = {0x02, 0x3C, 0x05, 0x10, 0x10, 0x03, 0x01, 0x03}; printf("-- Single CRC ----------\n"); oldCRC = 0x00; crc = 0x00; for (int i=0; i<3; i++){ crc = crc8FormByte( data[i], oldCRC); printf("DATA:%10d | CRC:%d (%02x)\n", data[i], crc, crc ); } printf("-- Serial CRC ----------\n"); oldCRC = 0x00; crc = 0x00; for (int i=2; i<7; i++){ oldCRC = crc; crc = crc8FormByte( data2[i], crc); printf( "DATA:%10d | CRC:%d (%02x)\t | OLD-CRC:%d (%02x)\n", data2[i], crc, crc, oldCRC, oldCRC ); } /* code */ return 0; }
the_stack_data/54825359.c
#include <stdio.h> #include <stdlib.h> #include <string.h> char* get_name_of_path(char* file_path); int main(int argc, char *argv[]) { int m = 0; char *name; name = get_name_of_path(argv[0]); while (m < 100) { char command[22]; sprintf(command, "cp %s %s%d", name, name, m); system(command); m++; } //printf("%s\n",name); free(name); return 0; } char* get_name_of_path(char* file_path) { int len = strlen(file_path); char result[20]; char *p = (char *) malloc(20); int count = -1; int j = 0; for (int i = len; i >= 0; i--) { if (file_path[i] == '/' || i == 0) { j = i; if (file_path[i] == '/') { j++; } for (j; j <= len; j++) { count++; result[count] = file_path[j]; } break; } } memset(p, 0, 20); strcpy(p, result); return p; }
the_stack_data/515514.c
#include <stdio.h> void fun (void) { printf ("Weak defined\n"); }
the_stack_data/532252.c
#include <stdio.h> int main() { int n, i, fat = 1; scanf("%d", &n); for (i = n; i >= 1; i--) { fat *= i; } printf("%d\n", fat); return 0; }
the_stack_data/1025014.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> int main() { FILE *f; char buffer[BUFSIZ + 1]; int chars_read; memset(buffer, 0, sizeof(buffer)); f = popen("uname -a", "r"); if (f != NULL) { chars_read = fread(buffer, sizeof(char), BUFSIZ, f); if (chars_read > 0) { printf("Output: %s \n", buffer); } pclose(f); return 0; } return EXIT_FAILURE; }
the_stack_data/1242500.c
int main(){ return 1; }
the_stack_data/2706.c
#include <stdio.h> int main() { int i = 0; for (;;) { if (i++ > 100) break; // loop body } return 0; }
the_stack_data/193893385.c
// BUG: unable to handle kernel NULL pointer dereference in should_fail // https://syzkaller.appspot.com/bug?id=8ef6ff5f114c32e5f49827f00838e06f74c90149 // status:invalid // autogenerated by syzkaller (http://github.com/google/syzkaller) #define _GNU_SOURCE #include <arpa/inet.h> #include <endian.h> #include <errno.h> #include <fcntl.h> #include <linux/capability.h> #include <linux/futex.h> #include <linux/if.h> #include <linux/if_ether.h> #include <linux/if_tun.h> #include <linux/ip.h> #include <linux/tcp.h> #include <net/if_arp.h> #include <pthread.h> #include <sched.h> #include <signal.h> #include <stdarg.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <sys/ioctl.h> #include <sys/mman.h> #include <sys/mount.h> #include <sys/prctl.h> #include <sys/resource.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/time.h> #include <sys/types.h> #include <sys/uio.h> #include <sys/wait.h> #include <unistd.h> __attribute__((noreturn)) static void doexit(int status) { volatile unsigned i; syscall(__NR_exit_group, status); for (i = 0;; i++) { } } #include <errno.h> #include <setjmp.h> #include <signal.h> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> const int kFailStatus = 67; const int kRetryStatus = 69; static void fail(const char* msg, ...) { int e = errno; va_list args; va_start(args, msg); vfprintf(stderr, msg, args); va_end(args); fprintf(stderr, " (errno %d)\n", e); doexit((e == ENOMEM || e == EAGAIN) ? kRetryStatus : kFailStatus); } static void exitf(const char* msg, ...) { int e = errno; va_list args; va_start(args, msg); vfprintf(stderr, msg, args); va_end(args); fprintf(stderr, " (errno %d)\n", e); doexit(kRetryStatus); } static __thread int skip_segv; static __thread jmp_buf segv_env; static void segv_handler(int sig, siginfo_t* info, void* uctx) { uintptr_t addr = (uintptr_t)info->si_addr; const uintptr_t prog_start = 1 << 20; const uintptr_t prog_end = 100 << 20; if (__atomic_load_n(&skip_segv, __ATOMIC_RELAXED) && (addr < prog_start || addr > prog_end)) { _longjmp(segv_env, 1); } doexit(sig); } static void install_segv_handler() { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = SIG_IGN; syscall(SYS_rt_sigaction, 0x20, &sa, NULL, 8); syscall(SYS_rt_sigaction, 0x21, &sa, NULL, 8); memset(&sa, 0, sizeof(sa)); sa.sa_sigaction = segv_handler; sa.sa_flags = SA_NODEFER | SA_SIGINFO; sigaction(SIGSEGV, &sa, NULL); sigaction(SIGBUS, &sa, NULL); } #define NONFAILING(...) \ { \ __atomic_fetch_add(&skip_segv, 1, __ATOMIC_SEQ_CST); \ if (_setjmp(segv_env) == 0) { \ __VA_ARGS__; \ } \ __atomic_fetch_sub(&skip_segv, 1, __ATOMIC_SEQ_CST); \ } static void use_temporary_dir() { char tmpdir_template[] = "./syzkaller.XXXXXX"; char* tmpdir = mkdtemp(tmpdir_template); if (!tmpdir) fail("failed to mkdtemp"); if (chmod(tmpdir, 0777)) fail("failed to chmod"); if (chdir(tmpdir)) fail("failed to chdir"); } static void vsnprintf_check(char* str, size_t size, const char* format, va_list args) { int rv; rv = vsnprintf(str, size, format, args); if (rv < 0) fail("tun: snprintf failed"); if ((size_t)rv >= size) fail("tun: string '%s...' doesn't fit into buffer", str); } static void snprintf_check(char* str, size_t size, const char* format, ...) { va_list args; va_start(args, format); vsnprintf_check(str, size, format, args); va_end(args); } #define COMMAND_MAX_LEN 128 #define PATH_PREFIX \ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin " #define PATH_PREFIX_LEN (sizeof(PATH_PREFIX) - 1) static void execute_command(bool panic, const char* format, ...) { va_list args; char command[PATH_PREFIX_LEN + COMMAND_MAX_LEN]; int rv; va_start(args, format); memcpy(command, PATH_PREFIX, PATH_PREFIX_LEN); vsnprintf_check(command + PATH_PREFIX_LEN, COMMAND_MAX_LEN, format, args); va_end(args); rv = system(command); if (rv) { if (panic) fail("command '%s' failed: %d", &command[0], rv); } } static int tunfd = -1; static int tun_frags_enabled; #define SYZ_TUN_MAX_PACKET_SIZE 1000 #define TUN_IFACE "syz_tun" #define LOCAL_MAC "aa:aa:aa:aa:aa:aa" #define REMOTE_MAC "aa:aa:aa:aa:aa:bb" #define LOCAL_IPV4 "172.20.20.170" #define REMOTE_IPV4 "172.20.20.187" #define LOCAL_IPV6 "fe80::aa" #define REMOTE_IPV6 "fe80::bb" #define IFF_NAPI 0x0010 #define IFF_NAPI_FRAGS 0x0020 static void initialize_tun(void) { tunfd = open("/dev/net/tun", O_RDWR | O_NONBLOCK); if (tunfd == -1) { printf("tun: can't open /dev/net/tun: please enable CONFIG_TUN=y\n"); printf("otherwise fuzzing or reproducing might not work as intended\n"); return; } const int kTunFd = 252; if (dup2(tunfd, kTunFd) < 0) fail("dup2(tunfd, kTunFd) failed"); close(tunfd); tunfd = kTunFd; struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); strncpy(ifr.ifr_name, TUN_IFACE, IFNAMSIZ); ifr.ifr_flags = IFF_TAP | IFF_NO_PI | IFF_NAPI | IFF_NAPI_FRAGS; if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) { ifr.ifr_flags = IFF_TAP | IFF_NO_PI; if (ioctl(tunfd, TUNSETIFF, (void*)&ifr) < 0) fail("tun: ioctl(TUNSETIFF) failed"); } if (ioctl(tunfd, TUNGETIFF, (void*)&ifr) < 0) fail("tun: ioctl(TUNGETIFF) failed"); tun_frags_enabled = (ifr.ifr_flags & IFF_NAPI_FRAGS) != 0; execute_command(1, "sysctl -w net.ipv6.conf.%s.accept_dad=0", TUN_IFACE); execute_command(1, "sysctl -w net.ipv6.conf.%s.router_solicitations=0", TUN_IFACE); execute_command(1, "ip link set dev %s address %s", TUN_IFACE, LOCAL_MAC); execute_command(1, "ip addr add %s/24 dev %s", LOCAL_IPV4, TUN_IFACE); execute_command(1, "ip -6 addr add %s/120 dev %s", LOCAL_IPV6, TUN_IFACE); execute_command(1, "ip neigh add %s lladdr %s dev %s nud permanent", REMOTE_IPV4, REMOTE_MAC, TUN_IFACE); execute_command(1, "ip -6 neigh add %s lladdr %s dev %s nud permanent", REMOTE_IPV6, REMOTE_MAC, TUN_IFACE); execute_command(1, "ip link set dev %s up", TUN_IFACE); } #define DEV_IPV4 "172.20.20.%d" #define DEV_IPV6 "fe80::%02hx" #define DEV_MAC "aa:aa:aa:aa:aa:%02hx" static void initialize_netdevices(void) { unsigned i; const char* devtypes[] = {"ip6gretap", "bridge", "vcan", "bond", "team"}; const char* devnames[] = {"lo", "sit0", "bridge0", "vcan0", "tunl0", "gre0", "gretap0", "ip_vti0", "ip6_vti0", "ip6tnl0", "ip6gre0", "ip6gretap0", "erspan0", "bond0", "veth0", "veth1", "team0", "veth0_to_bridge", "veth1_to_bridge", "veth0_to_bond", "veth1_to_bond", "veth0_to_team", "veth1_to_team"}; const char* devmasters[] = {"bridge", "bond", "team"}; for (i = 0; i < sizeof(devtypes) / (sizeof(devtypes[0])); i++) execute_command(0, "ip link add dev %s0 type %s", devtypes[i], devtypes[i]); execute_command(0, "ip link add type veth"); for (i = 0; i < sizeof(devmasters) / (sizeof(devmasters[0])); i++) { execute_command( 0, "ip link add name %s_slave_0 type veth peer name veth0_to_%s", devmasters[i], devmasters[i]); execute_command( 0, "ip link add name %s_slave_1 type veth peer name veth1_to_%s", devmasters[i], devmasters[i]); execute_command(0, "ip link set %s_slave_0 master %s0", devmasters[i], devmasters[i]); execute_command(0, "ip link set %s_slave_1 master %s0", devmasters[i], devmasters[i]); execute_command(0, "ip link set veth0_to_%s up", devmasters[i]); execute_command(0, "ip link set veth1_to_%s up", devmasters[i]); } execute_command(0, "ip link set bridge_slave_0 up"); execute_command(0, "ip link set bridge_slave_1 up"); for (i = 0; i < sizeof(devnames) / (sizeof(devnames[0])); i++) { char addr[32]; snprintf_check(addr, sizeof(addr), DEV_IPV4, i + 10); execute_command(0, "ip -4 addr add %s/24 dev %s", addr, devnames[i]); snprintf_check(addr, sizeof(addr), DEV_IPV6, i + 10); execute_command(0, "ip -6 addr add %s/120 dev %s", addr, devnames[i]); snprintf_check(addr, sizeof(addr), DEV_MAC, i + 10); execute_command(0, "ip link set dev %s address %s", devnames[i], addr); execute_command(0, "ip link set dev %s up", devnames[i]); } } static bool write_file(const char* file, const char* what, ...) { char buf[1024]; va_list args; va_start(args, what); vsnprintf(buf, sizeof(buf), what, args); va_end(args); buf[sizeof(buf) - 1] = 0; int len = strlen(buf); int fd = open(file, O_WRONLY | O_CLOEXEC); if (fd == -1) return false; if (write(fd, buf, len) != len) { int err = errno; close(fd); errno = err; return false; } close(fd); return true; } static void loop(); static void sandbox_common() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); setsid(); struct rlimit rlim; rlim.rlim_cur = rlim.rlim_max = 160 << 20; setrlimit(RLIMIT_AS, &rlim); rlim.rlim_cur = rlim.rlim_max = 8 << 20; setrlimit(RLIMIT_MEMLOCK, &rlim); rlim.rlim_cur = rlim.rlim_max = 136 << 20; setrlimit(RLIMIT_FSIZE, &rlim); rlim.rlim_cur = rlim.rlim_max = 1 << 20; setrlimit(RLIMIT_STACK, &rlim); rlim.rlim_cur = rlim.rlim_max = 0; setrlimit(RLIMIT_CORE, &rlim); if (unshare(CLONE_NEWNS)) { } if (unshare(CLONE_NEWIPC)) { } if (unshare(0x02000000)) { } if (unshare(CLONE_NEWUTS)) { } if (unshare(CLONE_SYSVSEM)) { } } static int real_uid; static int real_gid; __attribute__((aligned(64 << 10))) static char sandbox_stack[1 << 20]; static int namespace_sandbox_proc(void* arg) { sandbox_common(); write_file("/proc/self/setgroups", "deny"); if (!write_file("/proc/self/uid_map", "0 %d 1\n", real_uid)) fail("write of /proc/self/uid_map failed"); if (!write_file("/proc/self/gid_map", "0 %d 1\n", real_gid)) fail("write of /proc/self/gid_map failed"); if (unshare(CLONE_NEWNET)) fail("unshare(CLONE_NEWNET)"); initialize_tun(); initialize_netdevices(); if (mkdir("./syz-tmp", 0777)) fail("mkdir(syz-tmp) failed"); if (mount("", "./syz-tmp", "tmpfs", 0, NULL)) fail("mount(tmpfs) failed"); if (mkdir("./syz-tmp/newroot", 0777)) fail("mkdir failed"); if (mkdir("./syz-tmp/newroot/dev", 0700)) fail("mkdir failed"); unsigned mount_flags = MS_BIND | MS_REC | MS_PRIVATE; if (mount("/dev", "./syz-tmp/newroot/dev", NULL, mount_flags, NULL)) fail("mount(dev) failed"); if (mkdir("./syz-tmp/newroot/proc", 0700)) fail("mkdir failed"); if (mount(NULL, "./syz-tmp/newroot/proc", "proc", 0, NULL)) fail("mount(proc) failed"); if (mkdir("./syz-tmp/newroot/selinux", 0700)) fail("mkdir failed"); const char* selinux_path = "./syz-tmp/newroot/selinux"; if (mount("/selinux", selinux_path, NULL, mount_flags, NULL)) { if (errno != ENOENT) fail("mount(/selinux) failed"); if (mount("/sys/fs/selinux", selinux_path, NULL, mount_flags, NULL) && errno != ENOENT) fail("mount(/sys/fs/selinux) failed"); } if (mkdir("./syz-tmp/newroot/sys", 0700)) fail("mkdir failed"); if (mount(NULL, "./syz-tmp/newroot/sys", "sysfs", 0, NULL)) fail("mount(sysfs) failed"); if (mkdir("./syz-tmp/pivot", 0777)) fail("mkdir failed"); if (syscall(SYS_pivot_root, "./syz-tmp", "./syz-tmp/pivot")) { if (chdir("./syz-tmp")) fail("chdir failed"); } else { if (chdir("/")) fail("chdir failed"); if (umount2("./pivot", MNT_DETACH)) fail("umount failed"); } if (chroot("./newroot")) fail("chroot failed"); if (chdir("/")) fail("chdir failed"); struct __user_cap_header_struct cap_hdr = {}; struct __user_cap_data_struct cap_data[2] = {}; cap_hdr.version = _LINUX_CAPABILITY_VERSION_3; cap_hdr.pid = getpid(); if (syscall(SYS_capget, &cap_hdr, &cap_data)) fail("capget failed"); cap_data[0].effective &= ~(1 << CAP_SYS_PTRACE); cap_data[0].permitted &= ~(1 << CAP_SYS_PTRACE); cap_data[0].inheritable &= ~(1 << CAP_SYS_PTRACE); if (syscall(SYS_capset, &cap_hdr, &cap_data)) fail("capset failed"); loop(); doexit(1); } static int do_sandbox_namespace(void) { int pid; real_uid = getuid(); real_gid = getgid(); mprotect(sandbox_stack, 4096, PROT_NONE); pid = clone(namespace_sandbox_proc, &sandbox_stack[sizeof(sandbox_stack) - 64], CLONE_NEWUSER | CLONE_NEWPID, 0); if (pid < 0) fail("sandbox clone failed"); return pid; } static int inject_fault(int nth) { int fd; char buf[16]; fd = open("/proc/thread-self/fail-nth", O_RDWR); if (fd == -1) exitf("failed to open /proc/thread-self/fail-nth"); sprintf(buf, "%d", nth + 1); if (write(fd, buf, strlen(buf)) != (ssize_t)strlen(buf)) exitf("failed to write /proc/thread-self/fail-nth"); return fd; } static void execute_one(); extern unsigned long long procid; void loop() { while (1) { execute_one(); } } struct thread_t { int created, running, call; pthread_t th; }; static struct thread_t threads[16]; static void execute_call(int call); static int running; static int collide; static void* thr(void* arg) { struct thread_t* th = (struct thread_t*)arg; for (;;) { while (!__atomic_load_n(&th->running, __ATOMIC_ACQUIRE)) syscall(SYS_futex, &th->running, FUTEX_WAIT, 0, 0); execute_call(th->call); __atomic_fetch_sub(&running, 1, __ATOMIC_RELAXED); __atomic_store_n(&th->running, 0, __ATOMIC_RELEASE); syscall(SYS_futex, &th->running, FUTEX_WAKE); } return 0; } static void execute(int num_calls) { int call, thread; running = 0; for (call = 0; call < num_calls; call++) { for (thread = 0; thread < sizeof(threads) / sizeof(threads[0]); thread++) { struct thread_t* th = &threads[thread]; if (!th->created) { th->created = 1; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setstacksize(&attr, 128 << 10); pthread_create(&th->th, &attr, thr, th); } if (!__atomic_load_n(&th->running, __ATOMIC_ACQUIRE)) { th->call = call; __atomic_fetch_add(&running, 1, __ATOMIC_RELAXED); __atomic_store_n(&th->running, 1, __ATOMIC_RELEASE); syscall(SYS_futex, &th->running, FUTEX_WAKE); if (collide && call % 2) break; struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 20 * 1000 * 1000; syscall(SYS_futex, &th->running, FUTEX_WAIT, 1, &ts); if (running) usleep((call == num_calls - 1) ? 10000 : 1000); break; } } } } uint64_t r[1] = {0xffffffffffffffff}; unsigned long long procid; void execute_call(int call) { long res; switch (call) { case 0: res = syscall(__NR_socket, 0x26, 5, 0); if (res != -1) r[0] = res; break; case 1: NONFAILING(*(uint16_t*)0x20000080 = 0x26); NONFAILING( memcpy((void*)0x20000082, "\x72\x6e\x67\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 14)); NONFAILING(*(uint32_t*)0x20000090 = 0); NONFAILING(*(uint32_t*)0x20000094 = 0); NONFAILING(memcpy( (void*)0x20000098, "\x64\x72\x62\x67\x5f\x70\x72\x5f\x73\x68\x61\x35\x31\x32\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 64)); syscall(__NR_bind, r[0], 0x20000080, 0x58); break; case 2: write_file("/sys/kernel/debug/failslab/ignore-gfp-wait", "N"); write_file("/sys/kernel/debug/fail_futex/ignore-private", "N"); inject_fault(5); syscall(__NR_setsockopt, r[0], 0x117, 1, 0x200001c0, 0); break; } } void execute_one() { execute(3); collide = 1; execute(3); } int main() { syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0); char* cwd = get_current_dir_name(); for (procid = 0; procid < 8; procid++) { if (fork() == 0) { install_segv_handler(); for (;;) { if (chdir(cwd)) fail("failed to chdir"); use_temporary_dir(); int pid = do_sandbox_namespace(); int status = 0; while (waitpid(pid, &status, __WALL) != pid) { } } } } sleep(1000000); return 0; }
the_stack_data/57950629.c
#include <stdlib.h> #include <stdio.h> static void* return_arg(void* p); int frame3 ( void ) { int *a = malloc(20 * sizeof(int)); int i = 0; for(i = 0; i < 20; i++){ a[i] = 0; } int n = a[10]; if (a[5] == 42) { printf("hello from frame3(). The answer is 42.\n"); } else { printf("hello from frame3(). The answer is not 42.\n"); } n = a[ a[0] & 7 ]; free(a); a = malloc(99 * sizeof(int)); free(a); return n; } int frame2 ( void ) { return frame3() - 1; } int frame1 ( void ) { return frame2() + 1; } int main ( void ) { return frame1() - 1; } static void* return_arg(void* p) { return p; }
the_stack_data/29825253.c
/* * Copyright (c) 1980 Regents of the University of California. * All rights reserved. The Berkeley software License Agreement * specifies the terms and conditions for redistribution. */ /* * bcmp -- vax cmpc3 instruction */ int bcmp(v1, v2, length) const void *v1, *v2; unsigned long length; { register const char *b1 = v1; register const char *b2 = v2; if (length) do if (*b1++ != *b2++) break; while (--length); return(length); }
the_stack_data/63383.c
/* Description: Check README, * Notice(s): The data are in a .txt(cars.txt). */ #include <stdio.h> #include <stdlib.h> #include <strings.h> #include <ctype.h> typedef struct { //Includes all the variables to read a single line from cars.txt char m[25], c[25]; //25 characters is more than enough for the manufacturer & the color of the car int n, d; }car; void UI(int x) { //For easier management, a lot of the complex printing elements are stored and called from here int i; switch(x) { case 1: { //Horizontal double top line printf("\311"); for(i=0; i<77; i++) printf("\315"); printf("\273\n"); return; } case 2: { //Horizontal double middle line printf("\314"); for(i=0; i<77; i++) printf("\315"); printf("\271\n"); return; } case 3: { //Horizontal single middle line printf("\307"); for(i=0; i<77; i++) printf("\304"); printf("\266\n"); return; } case 4: { //Horizontal double bottom line printf("\310"); for(i=0; i<77; i++) printf("\315"); printf("\274\n"); return; } case 5: { //Stop and then clean printf("\n\n"); system("pause"); system("cls"); return; } case 6: { //Error message for(i=0; i<106; i++) printf("\260"); printf("Error: invalid_value..."); for(i=0; i<111; i++) printf("\260"); printf("\n"); return; } case 7: { //.txt Error message for(i=0; i<102; i++) printf("\260"); printf("Error opening the file \"cars.txt\"..."); for(i=0; i<102; i++) printf("\260"); return; } case 8: { //Search(5) message for(i=0; i<109; i++) printf("\260"); printf("No results found..."); for(i=0; i<112; i++) printf("\260"); break; } } } int display_scan() { //The menu that user sees when launching the program int in=-1; char temp[5]; UI(1); printf("\272 Developer: Thanasis Bounos%-37sVersion: 1.5 \272\n", ""); UI(2); printf("%-32sBasic Menu:%-35s\272\n", "\272", ""); UI(3); printf("\272 Choose one of the following:%-47s\272\n", ""); printf("\272%-4s%-73s\272\n", "", "1. Show all"); printf("\272%-4s%-73s\272\n", "", "2. Enter a new record"); printf("\272%-4s%-73s\272\n", "", "3. Delete a record"); printf("\272%-4s%-73s\272\n", "", "4. Modify a record"); printf("\272%-4s%-73s\272\n", "", "5. Search"); printf("\272%-4s%-73s\272\n", "", "6. Update database"); printf("\272%-4s%-73s\272\n", "", "0. Terminate"); UI(4); UI(1); printf("\272 To apply changes made to the database, you have to press six(6), else any%-3s\272\n\272 changes made will be lost.%-50s\272\n", "", ""); UI(4); do { //Ensures only: 0, 1, 2, 3, 4, 5, 6, will get returned in main printf("\n> "); scanf("%s", temp); in = atof(temp); if(temp[0]!='\60' && in!=1 && in!=2 && in!=3 && in!=4 && in!=5 && in!=6) UI(6); }while(temp[0]!='\60' && in!=1 && in!=2 && in!=3 && in!=4 && in!=5 && in!=6); return in; } int lines() { //"lines" returns the number of lines in "cars.txt" FILE *fl; char temp[100]; int i; if(!(fl = fopen("cars.txt", "r"))) UI(7); else { for(i=0; !feof(fl); i++) fgets(temp, 100, fl); fclose(fl); } return i; } void print() { //"print" is the fuction called when user selects 1. It prints all the records FILE *fl; int n; car a; if(fl = fopen("cars.txt", "r")) { n = lines(); //We get the number of records, so we can print it below UI(1); printf("%-26s1. Show all:(%d Records)%-28s\272\n", "\272", n, ""); UI(2); printf("\272 Reading \"cars.txt\"...%-54s\272\n", ""); UI(2); printf("\272%-4s%-15s%-15s%-22s%-21s\272\n", "", "Car Number", "Colour", "Manufacturer", "Purchase Date"); UI(3); while(!feof(fl)) { //Until the end of the file, we scan line-by-line the file and print it fscanf(fl, "%d %s %s %d", &a.n, a.c, a.m, &a.d); printf("\272%-4s%-15d%-15s%-22s%-21d\272\n", "", a.n, a.c, a.m, a.d); } UI(4); fclose(fl); } else UI(7); } car new_record(int x, int y) { //"new_record" is the fuction called when user selects 2(and 4). It asks and checks for the user input, to create a new record(or modify one) FILE *fl; int i, n=0, t; car a, *b; char temp[100]; if(fl = fopen("cars.txt", "r")) { n = lines(); //Counting the lines of cars.txt to create an array equal to that b = malloc(n*sizeof(car)); //Creating an array, in the exact dimesions of the txt for(i=0; i<n; i++) fscanf(fl, "%d %s %s %d", &b[i].n, b[i].c, b[i].m, &b[i].d); //Loading all the records of cars.txt to ram fclose(fl); } do { //Getting the new car number printf("%-15sWrite the car's number> ", ""); scanf("%s", temp); a.n = atof(temp); for(i=0, t=0; i<n; i++) if(a.n==b[i].n && b[i].n!=y) { t=-1; break; } //Checking that the number is not repeated if(a.n>9999 || a.n<1000 || t==-1) UI(6); }while(a.n>9999 || a.n<1000 || t==-1); if(fl = fopen("cars.txt", "r")) free(b); printf("%-15sWrite the car's colour> ", ""); //Getting the new car colour scanf("%s", a.c); printf("%-15sWrite the car's manufacturer> ", ""); //Getting the new car manufacturer scanf("%s", a.m); do { //Getting the new car purchase date printf("%-15sWrite the car's purchase date> ", ""); scanf("%s", temp); a.d = atof(temp); if(a.d>1959 || a.d<2007) UI(6); }while(a.d>2010 || a.d<1980); return a; } int bubblesort_scan() { //"bubblesort_scan" is the fuction called both for 3 and 4 FILE *fl; char temp[25]; int i, j, n=0, c=0, in=1; car *a, tmp; if(!(fl = fopen("cars.txt", "r"))) UI(7); else { n = lines(); //Getting the number of lines in cars.txt a = malloc(n*sizeof(car)); //Creating an equal array for(i=0; i<n; i++) fscanf(fl, "%d %s %s %d", &a[i].n, a[i].c, a[i].m, &a[i].d); //Loading the txt in RAM fclose(fl); for(i=1; i<n; i++) //Bubblesort for(j=0; j<n-1; j++) if(a[j].n>a[j+1].n) { tmp = a[j]; a[j] = a[j+1]; a[j+1] = tmp; } printf("%-5sAll the car numbers:%-53s\272\n", "\272", ""); //Printing the numbers UI(4); for(i=0; i<n; i++) printf("\t%d\t", a[i].n); do { //Input printf("\n\n> "); scanf("%s", temp); in = atof(temp); for(i=0; i<n && temp[0]!='\60'; i++) if(in==a[i].n) c=1; if(c==0) UI(6); }while(c==0); system("cls"); //Displaying the selected record UI(1); printf("\272%-4s%-15s%-15s%-22s%-21s\272\n", "", "Car Number", "Colour", "Manufacturer", "Purchase Date"); UI(3); for(i=0; i<n; i++) if(in==a[i].n) printf("\272%-4s%-15d%-15s%-22s%-21d\272\n", "", a[i].n, a[i].c, a[i].m, a[i].d); UI(4); free(a); return in; } } int search_display_scan() { //"search_display_scan" is the fuction called for displaying the search menu and getting the user's input int in; char temp[5]; UI(1); printf("%-32sSearch Menu:%-34s\272\n", "\272", ""); UI(3); printf("\272 Choose one of the following:%-47s\272\n", ""); printf("\272%-4s%-73s\272\n", "", "1. By number"); printf("\272%-4s%-73s\272\n", "", "2. By colour"); printf("\272%-4s%-73s\272\n", "", "3. By manufacturer"); printf("\272%-4s%-73s\272\n", "", "4. By manufacturing date"); printf("\272%-4s%-73s\272\n", "", "0. Return to basic menu"); UI(4); do { //Input printf("\n> "); scanf("%s", temp); in = atof(temp); if(temp[0]!='\60' && in!=1 && in!=2 && in!=3 && in!=4) UI(6); }while(temp[0]!='\60' && in!=1 && in!=2 && in!=3 && in!=4); return in; } void search_number(car x[], int size) { //"search_number" is the fuction called for searching by number int i, in, c=0; char cin, temp[5]; printf("%-28s5.1. Search - By Number:%-26s\272\n", "\272", ""); UI(2); printf("%-5sAll the car numbers:%-53s\272\n", "\272", ""); UI(4); for(i=0; i<size; i++) printf("\t%d\t", x[i].n); //printing all the numbers do { //getting the users input printf("\n\n> "); scanf(" %c%s", &cin, temp); in=atof(temp); if(temp[0]=='\60' || in<1000 || in>9999) UI(6); }while(temp[0]=='\60' || in<1000 || in>9999); system("cls"); switch(cin) { //Depending the user's choice, we show the results case '=': { //For = for(i=0; i<size; i++) { if(x[i].n==in) { //If true, then it is the record we are looking for UI(1); //Displaying the record printf("\272%-4s%-15s%-15s%-22s%-21s\272\n", "", "Car Number", "Colour", "Manufacturer", "Purchase Date"); UI(3); printf("\272%-4s%-15d%-15s%-22s%-21d\272\n", "", x[i].n, x[i].c, x[i].m, x[i].d); c=1; break; } } break; system("pause"); } case '>': { //For > for(i=0; i<size; i++) { if(x[i].n>in) { //If true, then it fits the user's choice if(c==0) { //This is to display the top part only once UI(1); printf("\272%-4s%-15s%-15s%-22s%-21s\272\n", "", "Car Number", "Colour", "Manufacturer", "Purchase Date"); UI(3); } printf("\272%-4s%-15d%-15s%-22s%-21d\272\n", "", x[i].n, x[i].c, x[i].m, x[i].d); //Displaying the record(s) c=1; } } break; } case '<': { //For < for(i=0; i<size; i++) { if(x[i].n<in) { //If true, then it fits the user's choice if(c==0) { //This is to display the top part only once UI(1); printf("\272%-4s%-15s%-15s%-22s%-21s\272\n", "", "Car Number", "Colour", "Manufacturer", "Purchase Date"); UI(3); } printf("\272%-4s%-15d%-15s%-22s%-21d\272\n", "", x[i].n, x[i].c, x[i].m, x[i].d); //Displaying the record(s) c=1; } } break; } } if(c==0) UI(8); //If nothing was found, we show the appropriate message else UI(4); //This is to display the bottom part only once } void search_colour(car x[], int size) { //"search_colour" is the fuction called for searching by colour int i, n=0, c, j; char in[25], temp[size][25]; printf("%-29s5.2. Search - By Colour:%-25s\272\n", "\272", ""); UI(2); printf("%-5sAll the car colours:%-53s\272\n", "\272", ""); UI(4); for(i=0; i<size; i++) { strcpy(temp[i], x[i].c); for(j=0, c=0; j<i; j++) if(!strcmp(temp[i], x[j].c)) c=1; //making sure the colour we are about to print, is not already printed if(c==0) printf("%-10s%-10s", "", temp[i]); //printing all the colours } printf("\n\n(Not case sensitive) > "); //getting the users input scanf("%s", in); system("cls"); n = strlen(in); for(i=0; in[i]; i++) in[i] = toupper(in[i]); //We make sure that the string is capital letters for(i=0, c=0; i<size; i++) if(!(strncmp(x[i].c, in, n))) { if(c==0) { //This is to display the top part only once UI(1); printf("\272%-4s%-15s%-15s%-22s%-21s\272\n", "", "Car Number", "Colour", "Manufacturer", "Purchase Date"); UI(3); } printf("\272%-4s%-15d%-15s%-22s%-21d\272\n", "", x[i].n, x[i].c, x[i].m, x[i].d); //Displaying the record(s) c=1; } if(c==0) UI(8); //If nothing was found, we show the appropriate message else UI(4); //This is to display the bottom part only once } void search_manufacturer(car x[], int size) { //"search_manufacturer" is the fuction called for searching by manufacturer int i, n, c, j; char in[25], temp[size][25]; printf("%-26s5.3. Search - By Manufacturer:%-22s\272\n", "\272", ""); UI(2); printf("%-5sAll the car manufacturers:%-47s\272\n", "\272", ""); UI(4); for(i=0; i<size; i++) { strcpy(temp[i], x[i].m); for(j=0, c=0; j<i; j++) if(!strcmp(temp[i], x[j].m)) c=1; //making sure the colour we are about to print, is not already printed if(c==0) printf("%-10s%-10s", "", temp[i]); //printing all the manufacturers } printf("\n\n(Not case sensitive) > "); //getting the users input scanf("%s", in); system("cls"); n = strlen(in); for(i=0; in[i]; i++) in[i] = toupper(in[i]); //We make sure that the string is capital letters for(i=0, c=0; i<size; i++) if(!(strncmp(x[i].m, in, n))) { if(c==0) { //This is to display the top part only once UI(1); printf("\272%-4s%-15s%-15s%-22s%-21s\272\n", "", "Car Number", "Colour", "Manufacturer", "Purchase Date"); UI(3); } printf("\272%-4s%-15d%-15s%-22s%-21d\272\n", "", x[i].n, x[i].c, x[i].m, x[i].d); //Displaying the record(s) c=1; } if(c==0) UI(8); //If nothing was found, we show the appropriate message else UI(4); //This is to display the bottom part only once } void search_date(car x[], int size) { //"search_date" is the fuction called for searching by date int i, in, c=0, j; char cin, temp[5]; printf("%-28s5.4. Search - By Date:%-28s\272\n", "\272", ""); UI(2); printf("%-5sAll the car manufacture dates:%-43s\272\n", "\272", ""); UI(4); for(i=0; i<size; i++) { for(j=0, c=0; j<i; j++) if(x[i].d==x[j].d) c=1; if(c==0) printf("\t%d\t", x[i].d); //printing all the numbers } do { //getting the users input printf("\n\n> "); scanf(" %c%s", &cin, temp); in=atof(temp); if(temp[0]=='\60' || in<1000 || in>9999) UI(6); }while(temp[0]=='\60' || in<1000 || in>9999); system("cls"); switch(cin) { //Depending the user's choice, we show the results case '=': { //For = for(i=0; i<size; i++) { if(x[i].d==in) { //If true, then it is the record we are looking for UI(1); //Displaying the record printf("\272%-4s%-15s%-15s%-22s%-21s\272\n", "", "Car Number", "Colour", "Manufacturer", "Purchase Date"); UI(3); printf("\272%-4s%-15d%-15s%-22s%-21d\272\n", "", x[i].n, x[i].c, x[i].m, x[i].d); c=1; break; } } break; } case '>': { //For > for(i=0, c=0; i<size; i++) { if(x[i].d>in) { //If true, then it fits the user's choice if(c==0) { UI(1); printf("\272%-4s%-15s%-15s%-22s%-21s\272\n", "", "Car Number", "Colour", "Manufacturer", "Purchase Date"); UI(3); } printf("\272%-4s%-15d%-15s%-22s%-21d\272\n", "", x[i].n, x[i].c, x[i].m, x[i].d); //Displaying the record(s) c=1; } } break; } case '<': { //For < for(i=0, c=0; i<size; i++) { if(x[i].d<in) { //If true, then it fits the user's choice if(c==0) { UI(1); printf("\272%-4s%-15s%-15s%-22s%-21s\272\n", "", "Car Number", "Colour", "Manufacturer", "Purchase Date"); UI(3); } printf("\272%-4s%-15d%-15s%-22s%-21d\272\n", "", x[i].n, x[i].c, x[i].m, x[i].d); //Displaying the record(s) c=1; } } break; } } if(c==0) UI(8); //If nothing was found, we show the appropriate message else UI(4); //This is to display the bottom part only once } void search_main() { //"search_main" is the 'main' for search(5) int in, i, n=0; FILE *fl; char temp[100]; car *a; if(!(fl = fopen("cars.txt", "r"))) UI(7); else { n = lines(); //Getting the txt's lines a = malloc(n*sizeof(car)); //Creating an equal array fclose(fl); fl = fopen("cars.txt", "r"); for(i=0; i<n; i++) fscanf(fl, "%d %s %s %d", &a[i].n, a[i].c, a[i].m, &a[i].d); //Loading the txt in RAM fclose(fl); } do { in = search_display_scan(); //Calling the interface and getting the user's input system("cls"); if(in!=0) UI(1); switch(in) { //Depending the user's choice we call the appropriate function case 1: { search_number(a, n); break; } case 2: { search_colour(a, n); break; } case 3: { search_manufacturer(a, n); break; } case 4: { search_date(a, n); break; } } if(in!=0) UI(5); }while(in!=0); if(fl = fopen("cars.txt", "r")) { free(a); fclose(fl); } } void update(int choice, car x, int t) { //"update" is the fuction called to update the txt with all the new details int i, j=0, tmp, c=0; FILE *fl; char temp[100]; car *a; if(!(fl = fopen("cars.txt", "r")) && choice!=1) UI(7); //If there is an error opening the txt, we show the appropriate message else if(!(fl = fopen("cars.txt", "r")) && choice==1) { //If there is an error opening the txt, but we have a new record, we create a new txt fl = fopen("cars.txt", "w"); fprintf(fl, "%d %s %s %d", x.n, x.c, x.m, x.d); fclose(fl); } else { //else either we delete a record or modify one for(j=0; !feof(fl); j++) fgets(temp, 100, fl); //Getting the lines of the txt a = malloc(j*sizeof(car)); //Creating an equal array tmp = strlen(temp); //Getting the lenght of the last line of the txt, so we can see if there is \n, or not rewind(fl); //Setting the cursor back to the top of the txt if(choice==1) { //If choice is 1, then we have a new record fclose(fl); fl = fopen("cars.txt", "a"); if(temp[tmp-1]!='\n') fprintf(fl, "\n"); //If we need a \n, we fprintf one fprintf(fl, "%d %s %s %d", x.n, x.c, x.m, x.d); //printing the new record } else { //For delete and modify for(i=0; i<j; i++) fscanf(fl, "%d %s %s %d", &a[i].n, a[i].c, a[i].m, &a[i].d); //Loading the txt to RAM fclose(fl); fl = fopen("cars.txt", "w"); switch(choice) { case 2: { //For delete for(i=0; i<j; i++) { if(!(t == a[i].n)) { //If it is the deleted record, we skip it if(c==0) { fprintf(fl, "%d %s %s %d", a[i].n, a[i].c, a[i].m, a[i].d); c=1; } else fprintf(fl, "\n%d %s %s %d", a[i].n, a[i].c, a[i].m, a[i].d); } } break; } case 3: { //For modify for(i=0; i<j; i++) { if(!(t == a[i].n)) { if(c==0) { fprintf(fl, "%d %s %s %d", a[i].n, a[i].c, a[i].m, a[i].d); c=1; } else fprintf(fl, "\n%d %s %s %d", a[i].n, a[i].c, a[i].m, a[i].d); } else { //If it is the modified record, we fprintf the new details if(c==0) { fprintf(fl, "%d %s %s %d", x.n, x.c, x.m, x.d); c=1; } else fprintf(fl, "\n%d %s %s %d", x.n, x.c, x.m, x.d); } } break; } } } fclose(fl); } } int main () { int in, i, temp=-1; car a = {0}; do { in = display_scan(); //Calling "display_scan" to get the users choice system("cls"); switch(in) { case 1: { print(); UI(5); break; } case 2: { //"new_record" is also used for modifying a record UI(1); printf("%-32s2. New record:%-32s\272\n", "\272", ""); UI(4); a = new_record(1, 0); //We save the input in a "car" variable called "a" temp=-1; system("cls"); break; } case 3: { //"bubblesort_scan" is also used for modifying a record UI(1); printf("%-32s3. Delete a record:%-27s\272\n", "\272", ""); UI(2); temp = bubblesort_scan(); //We save the number plate in a "int" variable called "temp" UI(5); break; } case 4: { //To modify a record we use the same fuction as delete(3), and new record(2) UI(1); printf("%-32s4. Modify a record:%-27s\272\n", "\272", ""); UI(2); temp = bubblesort_scan(); //We have to save both the number plate of the car we modified a = new_record(2, temp); //and the new details system("cls"); break; } case 5: { search_main(); //Calls "search_main", so user can choose the exact way to search system("cls"); break; } case 6: { if(a.n == 0 && temp==-1) { //Check to see if user has made any changes for(i=0; i<94; i++) printf("\260"); printf("Error: choose 2/3/4, and then update the database..."); for(i=0; i<94; i++) printf("\260"); printf("\n\n"); } else if(temp==-1) update(1, a, 0); //Calling fuction "update", to add a new record else if(a.n==0) update(2, a, temp); //Calling fuction "update", to delete a record else update(3, a, temp); //Calling fuction "update", to modify a record if(!(a.n == 0 && temp==-1)) { //Printing a success message for(i=0; i<108; i++) printf("\260"); printf("Updating Database..."); for(i=0; i<112; i++) printf("\260"); printf("\n\n"); a.n=0; temp=-1; } UI(5); break; } } }while(in!=0); //If user selects to terminate the program(0), then we escape the infite loop for(i=0; i<112; i++) printf("\260"); //Printing a "terminating" success message printf("Terminating..."); for(i=0; i<114; i++) printf("\260"); printf("\n\n"); system("pause"); return 0; }
the_stack_data/704886.c
/* Uninitialized pointer passed and used in a parameter. */ int f(int *ptr) { return *ptr << 7; } int main() { int *ptr, y; y = f(ptr); return y; }
the_stack_data/107953534.c
#include <errno.h> #include <signal.h> int sigaction(int sig, const struct sigaction* restrict sa, struct sigaction* restrict old) { errno = ENOSYS; return -1; }
the_stack_data/145451993.c
#define _GNU_SOURCE #include <sys/mount.h> #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <sched.h> #include <signal.h> #include <unistd.h> #define STACK_SIZE (1024*1024) static char child_stack[STACK_SIZE]; char* const child_args[] = { "/bin/bash", NULL }; int pipefd[2]; //pipefd[0] -> read, pipefd[1] -> write void set_uid(pid_t pid, int inside_id, int outside_id) { char path[256]; sprintf(path, "/proc/%d/uid_map", pid); FILE* uid_map = fopen(path, "w"); if (NULL == uid_map) { perror(path); return; } fprintf(uid_map,"%d %d %d", inside_id, outside_id, 1); fclose(uid_map); } void set_gid(pid_t pid, int inside_id, int outside_id) { char path[256]; sprintf(path, "/proc/%d/gid_map", pid); FILE* gid_map = fopen(path, "w"); if (NULL == gid_map) { perror(path); return; } fprintf(gid_map, "%d %d %d", inside_id, outside_id, 1); fclose(gid_map); } int container(void* args) { char ch; close(pipefd[1]); read(pipefd[0], &ch, 1); //wait parent process printf("[inside] Container Process ID %d, UID=%d, GID=%d\n", getpid(), getuid(), getgid()); //set hostname sethostname("NewContainer", 13); // make sure mount propagation is private mount("none", "/", NULL, MS_REC | MS_PRIVATE, NULL); // create a new mount /proc mount("proc", "/proc", "proc", 0, NULL); execv(child_args[0], child_args); return 1; } int main() { pipe(pipefd); printf("Container Parent Process %d\n", getpid()); printf("%d, %d\n", MS_BIND, MS_SHARED); int child_pid = clone(container, child_stack + STACK_SIZE, //The location of the stack used by child process, from child_stack to STACK_SIZE //CLONE_NEWUTS | SIGCHLD, //CLONE_NEWPID | CLONE_NEWIPC | CLONE_NEWUTS | SIGCHLD, CLONE_NEWNS | CLONE_NEWPID | CLONE_NEWIPC | CLONE_NEWUTS | SIGCHLD, //CLONE_NEWUSER cannot be supported by 3.10.0-514.21.1.el7.x86_64, may be supported by 4.0+ //CLONE_NEWUSER | CLONE_NEWNS | CLONE_NEWPID | CLONE_NEWIPC | CLONE_NEWUTS | SIGCHLD, NULL); if (-1 == child_pid) { perror("Failed to create child process"); return 1; } printf("[outside] Container Process ID %d, UID=%d, GID=%d\n", child_pid, getuid(), getgid()); //set_uid(child_pid, 0, getuid()); //set_gid(child_pid, 0, getgid()); sleep(10); close(pipefd[1]); // send a singal to notify child can start waitpid(child_pid, NULL, 0); printf("Container Parent Process End\n"); return 0; }
the_stack_data/220946.c
/****************************************************************************** * Exercise 1-11. How would you test the word count program? What kinds of input * are most likely to uncover bugs if there are any? * * BUG 1: Cumulation of random symbols such as !@#$% or numbers such as 12345 * are counted as words. * BUG 2: *******************************************************************************/ #include <stdio.h> #define IN 1 #define OUT 0 int main() { int c, nl, nw, nc, state; state = OUT; nl = nw = nc = 0; while ((c = getchar()) != EOF) { if (c == ' ' || c == '\n' || c == '\t') { state = OUT; } else if (state == OUT) { state = IN; ++nw; } } printf("%d %d %d\n", nl, nw, nc); }
the_stack_data/1097449.c
/* { dg-do run } */ #include <omp.h> extern void abort (void); #define LLONG_MAX __LONG_LONG_MAX__ #define ULLONG_MAX (LLONG_MAX * 2ULL + 1) #define INT_MAX __INT_MAX__ int arr[6 * 5]; void set (int loopidx, int idx) { #pragma omp atomic arr[loopidx * 5 + idx]++; } #define check(var, val, loopidx, idx) \ if (var == (val)) set (loopidx, idx); else #define test(loopidx, count) \ for (idx = 0; idx < 5; idx++) \ if (arr[loopidx * 5 + idx] != idx < count) \ abort (); \ else \ arr[loopidx * 5 + idx] = 0 int test1 (void) { int e = 0, idx; #pragma omp parallel reduction(+:e) { long long i; unsigned long long j; #pragma omp for schedule(dynamic,1) nowait for (i = LLONG_MAX - 30001; i <= LLONG_MAX - 10001; i += 10000) { check (i, LLONG_MAX - 30001, 0, 0) check (i, LLONG_MAX - 20001, 0, 1) check (i, LLONG_MAX - 10001, 0, 2) e = 1; } #pragma omp for schedule(dynamic,1) nowait for (i = -LLONG_MAX + 30000; i >= -LLONG_MAX + 10000; i -= 10000) { check (i, -LLONG_MAX + 30000, 1, 0) check (i, -LLONG_MAX + 20000, 1, 1) check (i, -LLONG_MAX + 10000, 1, 2) e = 1; } #pragma omp for schedule(dynamic,1) nowait for (j = 20; j <= LLONG_MAX - 70; j += LLONG_MAX + 50ULL) { check (j, 20, 2, 0) e = 1; } #pragma omp for schedule(dynamic,1) nowait for (j = ULLONG_MAX - 3; j >= LLONG_MAX + 70ULL; j -= LLONG_MAX + 50ULL) { check (j, ULLONG_MAX - 3, 3, 0) e = 1; } #pragma omp for schedule(dynamic,1) nowait for (j = LLONG_MAX - 20000ULL; j <= LLONG_MAX + 10000ULL; j += 10000ULL) { check (j, LLONG_MAX - 20000ULL, 4, 0) check (j, LLONG_MAX - 10000ULL, 4, 1) check (j, LLONG_MAX, 4, 2) check (j, LLONG_MAX + 10000ULL, 4, 3) e = 1; } #pragma omp for schedule(dynamic,1) nowait for (i = -3LL * INT_MAX - 20000LL; i <= INT_MAX + 10000LL; i += INT_MAX + 200LL) { check (i, -3LL * INT_MAX - 20000LL, 5, 0) check (i, -2LL * INT_MAX - 20000LL + 200LL, 5, 1) check (i, -INT_MAX - 20000LL + 400LL, 5, 2) check (i, -20000LL + 600LL, 5, 3) check (i, INT_MAX - 20000LL + 800LL, 5, 4) e = 1; } } if (e) abort (); test (0, 3); test (1, 3); test (2, 1); test (3, 1); test (4, 4); test (5, 5); return 0; } int test2 (void) { int e = 0, idx; #pragma omp parallel reduction(+:e) { long long i; unsigned long long j; #pragma omp for schedule(guided,1) nowait for (i = LLONG_MAX - 30001; i <= LLONG_MAX - 10001; i += 10000) { check (i, LLONG_MAX - 30001, 0, 0) check (i, LLONG_MAX - 20001, 0, 1) check (i, LLONG_MAX - 10001, 0, 2) e = 1; } #pragma omp for schedule(guided,1) nowait for (i = -LLONG_MAX + 30000; i >= -LLONG_MAX + 10000; i -= 10000) { check (i, -LLONG_MAX + 30000, 1, 0) check (i, -LLONG_MAX + 20000, 1, 1) check (i, -LLONG_MAX + 10000, 1, 2) e = 1; } #pragma omp for schedule(guided,1) nowait for (j = 20; j <= LLONG_MAX - 70; j += LLONG_MAX + 50ULL) { check (j, 20, 2, 0) e = 1; } #pragma omp for schedule(guided,1) nowait for (j = ULLONG_MAX - 3; j >= LLONG_MAX + 70ULL; j -= LLONG_MAX + 50ULL) { check (j, ULLONG_MAX - 3, 3, 0) e = 1; } #pragma omp for schedule(guided,1) nowait for (j = LLONG_MAX - 20000ULL; j <= LLONG_MAX + 10000ULL; j += 10000ULL) { check (j, LLONG_MAX - 20000ULL, 4, 0) check (j, LLONG_MAX - 10000ULL, 4, 1) check (j, LLONG_MAX, 4, 2) check (j, LLONG_MAX + 10000ULL, 4, 3) e = 1; } #pragma omp for schedule(guided,1) nowait for (i = -3LL * INT_MAX - 20000LL; i <= INT_MAX + 10000LL; i += INT_MAX + 200LL) { check (i, -3LL * INT_MAX - 20000LL, 5, 0) check (i, -2LL * INT_MAX - 20000LL + 200LL, 5, 1) check (i, -INT_MAX - 20000LL + 400LL, 5, 2) check (i, -20000LL + 600LL, 5, 3) check (i, INT_MAX - 20000LL + 800LL, 5, 4) e = 1; } } if (e) abort (); test (0, 3); test (1, 3); test (2, 1); test (3, 1); test (4, 4); test (5, 5); return 0; } int test3 (void) { int e = 0, idx; #pragma omp parallel reduction(+:e) { long long i; unsigned long long j; #pragma omp for schedule(static) nowait for (i = LLONG_MAX - 30001; i <= LLONG_MAX - 10001; i += 10000) { check (i, LLONG_MAX - 30001, 0, 0) check (i, LLONG_MAX - 20001, 0, 1) check (i, LLONG_MAX - 10001, 0, 2) e = 1; } #pragma omp for schedule(static) nowait for (i = -LLONG_MAX + 30000; i >= -LLONG_MAX + 10000; i -= 10000) { check (i, -LLONG_MAX + 30000, 1, 0) check (i, -LLONG_MAX + 20000, 1, 1) check (i, -LLONG_MAX + 10000, 1, 2) e = 1; } #pragma omp for schedule(static) nowait for (j = 20; j <= LLONG_MAX - 70; j += LLONG_MAX + 50ULL) { check (j, 20, 2, 0) e = 1; } #pragma omp for schedule(static) nowait for (j = ULLONG_MAX - 3; j >= LLONG_MAX + 70ULL; j -= LLONG_MAX + 50ULL) { check (j, ULLONG_MAX - 3, 3, 0) e = 1; } #pragma omp for schedule(static) nowait for (j = LLONG_MAX - 20000ULL; j <= LLONG_MAX + 10000ULL; j += 10000ULL) { check (j, LLONG_MAX - 20000ULL, 4, 0) check (j, LLONG_MAX - 10000ULL, 4, 1) check (j, LLONG_MAX, 4, 2) check (j, LLONG_MAX + 10000ULL, 4, 3) e = 1; } #pragma omp for schedule(static) nowait for (i = -3LL * INT_MAX - 20000LL; i <= INT_MAX + 10000LL; i += INT_MAX + 200LL) { check (i, -3LL * INT_MAX - 20000LL, 5, 0) check (i, -2LL * INT_MAX - 20000LL + 200LL, 5, 1) check (i, -INT_MAX - 20000LL + 400LL, 5, 2) check (i, -20000LL + 600LL, 5, 3) check (i, INT_MAX - 20000LL + 800LL, 5, 4) e = 1; } } if (e) abort (); test (0, 3); test (1, 3); test (2, 1); test (3, 1); test (4, 4); test (5, 5); return 0; } int test4 (void) { int e = 0, idx; #pragma omp parallel reduction(+:e) { long long i; unsigned long long j; #pragma omp for schedule(static,1) nowait for (i = LLONG_MAX - 30001; i <= LLONG_MAX - 10001; i += 10000) { check (i, LLONG_MAX - 30001, 0, 0) check (i, LLONG_MAX - 20001, 0, 1) check (i, LLONG_MAX - 10001, 0, 2) e = 1; } #pragma omp for schedule(static,1) nowait for (i = -LLONG_MAX + 30000; i >= -LLONG_MAX + 10000; i -= 10000) { check (i, -LLONG_MAX + 30000, 1, 0) check (i, -LLONG_MAX + 20000, 1, 1) check (i, -LLONG_MAX + 10000, 1, 2) e = 1; } #pragma omp for schedule(static,1) nowait for (j = 20; j <= LLONG_MAX - 70; j += LLONG_MAX + 50ULL) { check (j, 20, 2, 0) e = 1; } #pragma omp for schedule(static,1) nowait for (j = ULLONG_MAX - 3; j >= LLONG_MAX + 70ULL; j -= LLONG_MAX + 50ULL) { check (j, ULLONG_MAX - 3, 3, 0) e = 1; } #pragma omp for schedule(static,1) nowait for (j = LLONG_MAX - 20000ULL; j <= LLONG_MAX + 10000ULL; j += 10000ULL) { check (j, LLONG_MAX - 20000ULL, 4, 0) check (j, LLONG_MAX - 10000ULL, 4, 1) check (j, LLONG_MAX, 4, 2) check (j, LLONG_MAX + 10000ULL, 4, 3) e = 1; } #pragma omp for schedule(static,1) nowait for (i = -3LL * INT_MAX - 20000LL; i <= INT_MAX + 10000LL; i += INT_MAX + 200LL) { check (i, -3LL * INT_MAX - 20000LL, 5, 0) check (i, -2LL * INT_MAX - 20000LL + 200LL, 5, 1) check (i, -INT_MAX - 20000LL + 400LL, 5, 2) check (i, -20000LL + 600LL, 5, 3) check (i, INT_MAX - 20000LL + 800LL, 5, 4) e = 1; } } if (e) abort (); test (0, 3); test (1, 3); test (2, 1); test (3, 1); test (4, 4); test (5, 5); return 0; } int test5 (void) { int e = 0, idx; #pragma omp parallel reduction(+:e) { long long i; unsigned long long j; #pragma omp for schedule(runtime) nowait for (i = LLONG_MAX - 30001; i <= LLONG_MAX - 10001; i += 10000) { check (i, LLONG_MAX - 30001, 0, 0) check (i, LLONG_MAX - 20001, 0, 1) check (i, LLONG_MAX - 10001, 0, 2) e = 1; } #pragma omp for schedule(runtime) nowait for (i = -LLONG_MAX + 30000; i >= -LLONG_MAX + 10000; i -= 10000) { check (i, -LLONG_MAX + 30000, 1, 0) check (i, -LLONG_MAX + 20000, 1, 1) check (i, -LLONG_MAX + 10000, 1, 2) e = 1; } #pragma omp for schedule(runtime) nowait for (j = 20; j <= LLONG_MAX - 70; j += LLONG_MAX + 50ULL) { check (j, 20, 2, 0) e = 1; } #pragma omp for schedule(runtime) nowait for (j = ULLONG_MAX - 3; j >= LLONG_MAX + 70ULL; j -= LLONG_MAX + 50ULL) { check (j, ULLONG_MAX - 3, 3, 0) e = 1; } #pragma omp for schedule(runtime) nowait for (j = LLONG_MAX - 20000ULL; j <= LLONG_MAX + 10000ULL; j += 10000ULL) { check (j, LLONG_MAX - 20000ULL, 4, 0) check (j, LLONG_MAX - 10000ULL, 4, 1) check (j, LLONG_MAX, 4, 2) check (j, LLONG_MAX + 10000ULL, 4, 3) e = 1; } #pragma omp for schedule(runtime) nowait for (i = -3LL * INT_MAX - 20000LL; i <= INT_MAX + 10000LL; i += INT_MAX + 200LL) { check (i, -3LL * INT_MAX - 20000LL, 5, 0) check (i, -2LL * INT_MAX - 20000LL + 200LL, 5, 1) check (i, -INT_MAX - 20000LL + 400LL, 5, 2) check (i, -20000LL + 600LL, 5, 3) check (i, INT_MAX - 20000LL + 800LL, 5, 4) e = 1; } } if (e) abort (); test (0, 3); test (1, 3); test (2, 1); test (3, 1); test (4, 4); test (5, 5); return 0; } int main (void) { if (2 * sizeof (int) != sizeof (long long)) return 0; test1 (); test2 (); test3 (); test4 (); omp_set_schedule (omp_sched_static, 0); test5 (); omp_set_schedule (omp_sched_static, 3); test5 (); omp_set_schedule (omp_sched_dynamic, 5); test5 (); omp_set_schedule (omp_sched_guided, 2); test5 (); return 0; }
the_stack_data/145452748.c
#include <stdlib.h> #include <stdio.h> #include <time.h> #include <pthread.h> static pthread_mutex_t lrand_mutex = PTHREAD_MUTEX_INITIALIZER; void generate_uuid(char* buf) { pthread_mutex_lock(&lrand_mutex); long a = lrand48(); long b = lrand48(); long c = lrand48(); long d = lrand48(); pthread_mutex_unlock(&lrand_mutex); // SID must match this regex for Kount compat /^\w{1,32}$/ sprintf(buf, "frontend=%08lx%04lx%04lx%04lx%04lx%08lx", a, b & 0xffff, (b & ((long)0x0fff0000) >> 16) | 0x4000, (c & 0x0fff) | 0x8000, (c & (long)0xffff0000) >> 16, d ); return; }
the_stack_data/92324607.c
int number_returner(void); int main(void) { return number_returner() == 100 ? 0 : 1; }
the_stack_data/190769239.c
#include <stdio.h> enum access_type{ ACC_READ, ACC_WRITE }; int main(int argc, char** argv) { printf("ACC_WRITE=%d ACC_READ=%d\n" ,ACC_WRITE ,ACC_READ); printf("%s\n", ACC_WRITE ? "ACC_WRITE is true" : "ACC_WRITE is false"); printf("%s\n", ACC_READ? "ACC_READ is true" : "ACC_READ is false"); }
the_stack_data/46996.c
#include<stdio.h> #include<math.h> void main() { double x1,x2,y1,y2,d; printf("Enter coordinates of 1st point "); scanf("%lf%lf",&x1,&y1); printf("\nEnter coordinates of 2nd point "); scanf("%lf%lf",&x2,&y2); d = sqrt(pow((x2 - x1),2) + pow((y2 - y1),2)); printf("The distance between the points is: %lf",d); }