file
stringlengths
18
26
data
stringlengths
2
1.05M
the_stack_data/165765253.c
#include<stdio.h> #include<stdlib.h> #include<errno.h> #include<fcntl.h> #include<string.h> #include<unistd.h> #define BUFFER_LENGTH 1000 ///< The buffer length (crude but fine) static char receive[BUFFER_LENGTH]; ///< The receive buffer from the LKM int main(){ int ret, fd; char stringToSend[BUFFER_LENGTH]; printf("Starting device test code example...\n"); fd = open("/dev/ebbchar", O_RDWR); // Open the device with read/write access if (fd < 0){ perror("Failed to open the device..."); return errno; } printf("Type in a short string to send to the kernel module:\n"); scanf("%[^\n]%*c", stringToSend); // Read in a string (with spaces) printf("Writing message to the device [%s].\n", stringToSend); ret = write(fd, stringToSend, strlen(stringToSend)); // Send the string to the LKM if (ret < 0){ perror("Failed to write the message to the device."); return errno; } printf("Press ENTER to read back from the device...\n"); getchar(); printf("Reading from the device...\n"); ret = read(fd, receive, BUFFER_LENGTH); // Read the response from the LKM if (ret < 0){ perror("Failed to read the message from the device."); return errno; } printf("The received message is: [%s]\n", receive); printf("End of the program\n"); return 0; }
the_stack_data/148189.c
#include<stdio.h> #include<math.h> int main() { int num_1,num_2,res; scanf("%d", &num_1); scanf("%d", &num_2); res = pow (num_1, num_2); printf("%d\n", res); return 0; }
the_stack_data/40438.c
#include<stdio.h> int main(){ // Assuming non-leap year float num = 365; float denom = 365; float pr; int n = 0; printf("Probability to find : "); scanf("%f", &pr); float p = 1; while (p > pr){ p *= (num/denom); num--; n++; } printf("\nTotal no. of people out of which there " " is %0.1f probability that two of them " "have same birthdays is %d ", p, n); return 0; }
the_stack_data/121843.c
/* Matrix Vector multiplication with the Matrix partially missing on Accelerator. Using the target enter data construct. The missing matrix will be copied implicitly as well as the result vector "c", but c will be copied out a second time resulting in a cuda error. */ #include <stdio.h> #include <stdbool.h> #include <stdlib.h> #define C 512 int *a; int *b; int *c; int init(){ for(int i=0; i<C; i++){ for(int j=0; j<C; j++){ b[j+i*C]=1; } a[i]=1; c[i]=0; } return 0; } int Mult(){ #pragma acc enter data copyin(a[0:C]) create(c[0:C]) { #pragma acc parallel loop gang for(int i=0; i<C; i++){ #pragma acc loop worker for(int j=0; j<C; j++){ c[i]+=b[j+i*C]*a[j]; } } } #pragma acc exit data copyout(c[0:C]) delete(a[0:C]) return 0; } int check(){ bool test = false; for(int i=0; i<C; i++){ if(c[i]!=C){ test = true; } } printf("Memory Access Issue visible: %s\n",test ? "true" : "false"); return 0; } int main(){ a = malloc(C*sizeof(int)); b = malloc(C*C*sizeof(int)); c = malloc(C*sizeof(int)); init(); Mult(); check(); free(a); free(b); free(c); return 0; }
the_stack_data/1110696.c
#include <assert.h> #ifdef __cplusplus extern "C" #endif char mkstemp(); int main() { #if defined (__stub_mkstemp) || defined (__stub___mkstemp) fail fail fail #else mkstemp(); #endif return 0; }
the_stack_data/1260133.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/stat.h> #include <fcntl.h> #include <arpa/inet.h> char error_msg[] = "E"; char yes_msg[] = "L"; void error(const char *msg) { perror(msg); exit(1); } int main(int argc, char* argv[]){ int socket_id, new_socket_id, msg_len; struct sockaddr_in server, client; //details of server and client socklen_t client_len; int portno = 8001; int b = 20; char buffer[100]; //buffer to store client message and word array reads word from the file socket_id = socket(AF_INET, SOCK_STREAM, 0); //opening a socket corresponding the the UDP protocol if(socket_id < 0){ error("socket()"); } bzero(&server, sizeof(server)); //initializing with 0s in the memory server.sin_family = AF_INET; //going to communicate over the internt server.sin_addr.s_addr = INADDR_ANY; //open to all network server.sin_port = htons(portno); //converting the port to network byte order format if(bind(socket_id, (struct sockaddr*) &server, sizeof(server)) < 0){ error("bind()"); } int n; listen(socket_id, 5); while(1) { new_socket_id = accept(socket_id, (struct sockaddr *) &client, &client_len); if(new_socket_id < 0) error("accept()"); // else // printf("connection established\n\n"); bzero(buffer,100); msg_len = recv(new_socket_id, buffer, 99, MSG_WAITALL); if(msg_len < 0) error("read"); // buffer[strlen(buffer)-1] = '\0'; //removing the newline character (\n) int file_fd = open(buffer, O_RDONLY); //opening the file in read only mode // if the file doesn't exist // send 'E' if(file_fd == -1) { n = send(new_socket_id, error_msg, strlen(error_msg), 0 ); close(new_socket_id); close(socket_id); exit(0); return 0; } // else send 'L' // also send file_size n = send(new_socket_id, yes_msg, strlen(yes_msg), 0 ); struct stat st; stat(buffer, &st); int file_size = st.st_size; // printf("\tt:%d\n", file_size ); int tot = 100; char i_to_s[tot]; sprintf(i_to_s, "%d", file_size); // printf("\t:%s\n", i_to_s ); n = send(new_socket_id, i_to_s, strlen(i_to_s), 0 ); int q,r; q = file_size/(b); r = file_size%(b); bzero(buffer, sizeof(buffer)); while(q--) { n = read(file_fd, buffer, b); // buffer[b-1]='\0'; printf("%d ",n ); n = send(new_socket_id, buffer, b, 0 ); printf("T:%d %d\n", (file_size/b)-q , n ); bzero(buffer, sizeof(buffer)); } // last block // if(r!=0) // { n = read(file_fd, buffer, r); printf("%d ",n ); n = send(new_socket_id, buffer, r, 0 ); printf("T:%d %d\n", (file_size/b)-q , n ); bzero(buffer, sizeof(buffer)); close(new_socket_id); close(file_fd); // } } close(socket_id); exit(0); return 0; }
the_stack_data/98774.c
#include <stdio.h> #include <stdlib.h> void swap_int(int p1, int p2); //Function Prototype int main(int argc, char *argv[]) //Main Function or Calling Function { int _arg1=0; //Actual arguments int _arg2=0; printf("Enter _arg1 & _arg2\n"); scanf("%d %d", &_arg1, &_arg2); printf("Before swapping\n"); printf("_arg1:%d _arg2:%d\n", _arg1, _arg2); swap_int(_arg1, _arg2); //Function invoking statement printf("After swapping\n"); printf("_arg1:%d _arg2:%d\n", _arg1, _arg2); system("PAUSE"); return 0; } void swap_int(int p1, int p2) //Function Defination { int temp=0; //p1 & p2 are formal arguments temp = p1; p1 = p2; p2 = temp; }
the_stack_data/10870.c
#include <stdio.h> #define DIM 30 int baricentro(int a[], int n); int main(void) { int arr[DIM], h, i, inxb; do { printf("Inserisci numero elementi array: "); scanf("%d", &h); }while(h<=0); for(i=0;i<h;i++) { printf("Inserisci elemento %d: ", i+1); scanf("%d", &arr[i]); } inxb = baricentro(arr, h); if(inxb != -1) printf("Indice primo baricentro: %d\n", inxb); else printf("Nessun baricentro trovato.\n"); return 0; } int baricentro(int a[], int n) { int i, j, s1, s2; for(i=0;i<n;i++) { s1=0; s2=0; for(j=0;j<=i;j++) s1 += a[j]; for(j=i+1;j<n;j++) s2 += a[j]; if(s1 == s2) return i; } return -1; }
the_stack_data/331659.c
/* Generated by CIL v. 1.7.0 */ /* print_CIL_Input is false */ struct _IO_FILE; struct timeval; extern void signal(int sig , void *func ) ; extern float strtof(char const *str , char const *endptr ) ; 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 char input[1] , unsigned char 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 , ...) ; int main(int argc , char *argv[] ) { unsigned char input[1] ; unsigned char output[1] ; int randomFuns_i5 ; unsigned char 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 char )strtoul(argv[randomFuns_i5 + 1], 0, 10); input[randomFuns_i5] = randomFuns_value6; randomFuns_i5 ++; } RandomFunc(input, output); if (output[0] == 228) { printf("You win!\n"); } else { } randomFuns_main_i7 = 0; while (randomFuns_main_i7 < 1) { printf("%u\n", output[randomFuns_main_i7]); randomFuns_main_i7 ++; } } } void megaInit(void) { { } } void RandomFunc(unsigned char input[1] , unsigned char output[1] ) { unsigned char state[1] ; unsigned char local2 ; unsigned char local1 ; { state[0UL] = (input[0UL] + 914778474UL) * (unsigned char)22; local1 = 0UL; while (local1 < 1UL) { local2 = 0UL; while (local2 < 1UL) { if (state[0UL] < local2 + local1) { state[local2] += state[0UL]; state[0UL] *= state[0UL]; } else { state[0UL] *= state[0UL]; state[0UL] = state[local1] * state[local2]; } local2 ++; } local1 ++; } output[0UL] = state[0UL] - 507365164UL; } }
the_stack_data/797633.c
#include <stdio.h> #include <string.h> void print_strings(char * [], int); void stsrt(char * [], int, int); char * s_gets(char *, int); int main(void) { char input[10][80]; char * s1[10]; int ct = 0; printf("Enter:"); while (ct < 10 && s_gets(input[ct], 80) != NULL && input[ct][0] != '\0') { s1[ct] = input[ct]; ct++; } printf("请选择:\n"); printf("0. print\n"); printf("1. ASCII\n"); printf("2. strlen:\n"); printf("3. word:\n"); printf("4. quit:\n"); while (1) { int choice; scanf("%d", &choice); switch (choice) { case 0: print_strings(s1, 10); break; case 1: case 2: case 3: stsrt(s1, 10, choice); print_strings(s1, 10); break; default: return 0; break; } } return 0; } void print_strings(char * strings [], int num) { int i; for (i = 0; i < num; i++) { printf("%s\n", strings[i]); } } void stsrt(char * strings [], int num, int type) { char *temp; int top, seek; for (top = 0; top < num - 1; top++) { for (seek = top; seek < num; seek++) { int result = 0; switch (type) { case 1: result = strcmp(strings[top], strings[seek]); break; case 2: result = strlen(strings[top]) - strlen(strings[seek]); break; case 3: result = strlen(strings[top]) - strlen(strings[seek]); break; default: break; } if (result > 0) { temp = strings[top]; strings[top] = strings[seek]; strings[seek] = temp; } } } } char * s_gets(char * st, int n) { char * ret_val; int i = 0; ret_val = fgets(st, n, stdin); if (ret_val) { while (st[i] != '\n' && st[i] != '\0') { i++; } if (st[i] == '\n') st[i] = '\0'; else { while (getchar() != '\n') { continue; } } } return ret_val; }
the_stack_data/243893040.c
/* Copyright (C) 2011-2015 P.D. Buchan ([email protected]) 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, see <http://www.gnu.org/licenses/>. */ // Send an IPv4 ARP packet via raw socket at the link layer (ethernet frame). // Values set for ARP request. #include <stdio.h> #include <stdlib.h> #include <unistd.h> // close() #include <string.h> // strcpy, memset(), and memcpy() #include <netdb.h> // struct addrinfo #include <sys/types.h> // needed for socket(), uint8_t, uint16_t #include <sys/socket.h> // needed for socket() #include <netinet/in.h> // IPPROTO_RAW, INET_ADDRSTRLEN #include <netinet/ip.h> // IP_MAXPACKET (which is 65535) #include <arpa/inet.h> // inet_pton() and inet_ntop() #include <sys/ioctl.h> // macro ioctl is defined #include <bits/ioctls.h> // defines values for argument "request" of ioctl. #include <net/if.h> // struct ifreq #include <linux/if_ether.h> // ETH_P_ARP = 0x0806 #include <linux/if_packet.h> // struct sockaddr_ll (see man 7 packet) #include <net/ethernet.h> #include <errno.h> // errno, perror() // Define a struct for ARP header typedef struct _arp_hdr arp_hdr; struct _arp_hdr { uint16_t htype; uint16_t ptype; uint8_t hlen; uint8_t plen; uint16_t opcode; uint8_t sender_mac[6]; uint8_t sender_ip[4]; uint8_t target_mac[6]; uint8_t target_ip[4]; }; // Define some constants. #define ETH_HDRLEN 14 // Ethernet header length #define IP4_HDRLEN 20 // IPv4 header length #define ARP_HDRLEN 28 // ARP header length #define ARPOP_REQUEST 1 // Taken from <linux/if_arp.h> // Function prototypes char *allocate_strmem (int); uint8_t *allocate_ustrmem (int); int main (int argc, char **argv) { int i, status, frame_length, sd, bytes; char *interface, *target, *src_ip; arp_hdr arphdr; uint8_t *src_mac, *dst_mac, *ether_frame; struct addrinfo hints, *res; struct sockaddr_in *ipv4; struct sockaddr_ll device; struct ifreq ifr; // Allocate memory for various arrays. src_mac = allocate_ustrmem (6); dst_mac = allocate_ustrmem (6); ether_frame = allocate_ustrmem (IP_MAXPACKET); interface = allocate_strmem (40); target = allocate_strmem (40); src_ip = allocate_strmem (INET_ADDRSTRLEN); // Interface to send packet through. strcpy (interface, "eth0"); // Submit request for a socket descriptor to look up interface. if ((sd = socket (AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0) { perror ("socket() failed to get socket descriptor for using ioctl() "); exit (EXIT_FAILURE); } // Use ioctl() to look up interface name and get its MAC address. memset (&ifr, 0, sizeof (ifr)); snprintf (ifr.ifr_name, sizeof (ifr.ifr_name), "%s", interface); if (ioctl (sd, SIOCGIFHWADDR, &ifr) < 0) { perror ("ioctl() failed to get source MAC address "); return (EXIT_FAILURE); } close (sd); // Copy source MAC address. memcpy (src_mac, ifr.ifr_hwaddr.sa_data, 6 * sizeof (uint8_t)); // Report source MAC address to stdout. printf ("MAC address for interface %s is ", interface); for (i=0; i<5; i++) { printf ("%02x:", src_mac[i]); } printf ("%02x\n", src_mac[5]); // Find interface index from interface name and store index in // struct sockaddr_ll device, which will be used as an argument of sendto(). memset (&device, 0, sizeof (device)); if ((device.sll_ifindex = if_nametoindex (interface)) == 0) { perror ("if_nametoindex() failed to obtain interface index "); exit (EXIT_FAILURE); } printf ("Index for interface %s is %i\n", interface, device.sll_ifindex); // Set destination MAC address: broadcast address memset (dst_mac, 0xff, 6 * sizeof (uint8_t)); // Source IPv4 address: you need to fill this out strcpy (src_ip, "10.0.0.20"); // Destination URL or IPv4 address (must be a link-local node): you need to fill this out strcpy (target, "10.0.0.22"); // Fill out hints for getaddrinfo(). memset (&hints, 0, sizeof (struct addrinfo)); hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = hints.ai_flags | AI_CANONNAME; // Source IP address if ((status = inet_pton (AF_INET, src_ip, &arphdr.sender_ip)) != 1) { fprintf (stderr, "inet_pton() failed for source IP address.\nError message: %s", strerror (status)); exit (EXIT_FAILURE); } // Resolve target using getaddrinfo(). if ((status = getaddrinfo (target, NULL, &hints, &res)) != 0) { fprintf (stderr, "getaddrinfo() failed: %s\n", gai_strerror (status)); exit (EXIT_FAILURE); } ipv4 = (struct sockaddr_in *) res->ai_addr; memcpy (&arphdr.target_ip, &ipv4->sin_addr, 4 * sizeof (uint8_t)); freeaddrinfo (res); // Fill out sockaddr_ll. device.sll_family = AF_PACKET; memcpy (device.sll_addr, src_mac, 6 * sizeof (uint8_t)); device.sll_halen = 6; // ARP header // Hardware type (16 bits): 1 for ethernet arphdr.htype = htons (1); // Protocol type (16 bits): 2048 for IP arphdr.ptype = htons (ETH_P_IP); // Hardware address length (8 bits): 6 bytes for MAC address arphdr.hlen = 6; // Protocol address length (8 bits): 4 bytes for IPv4 address arphdr.plen = 4; // OpCode: 1 for ARP request arphdr.opcode = htons (ARPOP_REQUEST); // Sender hardware address (48 bits): MAC address memcpy (&arphdr.sender_mac, src_mac, 6 * sizeof (uint8_t)); // Sender protocol address (32 bits) // See getaddrinfo() resolution of src_ip. // Target hardware address (48 bits): zero, since we don't know it yet. memset (&arphdr.target_mac, 0, 6 * sizeof (uint8_t)); // Target protocol address (32 bits) // See getaddrinfo() resolution of target. // Fill out ethernet frame header. // Ethernet frame length = ethernet header (MAC + MAC + ethernet type) + ethernet data (ARP header) frame_length = 6 + 6 + 2 + ARP_HDRLEN; // Destination and Source MAC addresses memcpy (ether_frame, dst_mac, 6 * sizeof (uint8_t)); memcpy (ether_frame + 6, src_mac, 6 * sizeof (uint8_t)); // Next is ethernet type code (ETH_P_ARP for ARP). // http://www.iana.org/assignments/ethernet-numbers ether_frame[12] = ETH_P_ARP / 256; ether_frame[13] = ETH_P_ARP % 256; // Next is ethernet frame data (ARP header). // ARP header memcpy (ether_frame + ETH_HDRLEN, &arphdr, ARP_HDRLEN * sizeof (uint8_t)); // Submit request for a raw socket descriptor. if ((sd = socket (PF_PACKET, SOCK_RAW, htons (ETH_P_ALL))) < 0) { perror ("socket() failed "); exit (EXIT_FAILURE); } // Send ethernet frame to socket. if ((bytes = sendto (sd, ether_frame, frame_length, 0, (struct sockaddr *) &device, sizeof (device))) <= 0) { perror ("sendto() failed"); exit (EXIT_FAILURE); } // Close socket descriptor. close (sd); // Free allocated memory. free (src_mac); free (dst_mac); free (ether_frame); free (interface); free (target); free (src_ip); return (EXIT_SUCCESS); } // Allocate memory for an array of chars. char * allocate_strmem (int len) { void *tmp; if (len <= 0) { fprintf (stderr, "ERROR: Cannot allocate memory because len = %i in allocate_strmem().\n", len); exit (EXIT_FAILURE); } tmp = (char *) malloc (len * sizeof (char)); if (tmp != NULL) { memset (tmp, 0, len * sizeof (char)); return (tmp); } else { fprintf (stderr, "ERROR: Cannot allocate memory for array allocate_strmem().\n"); exit (EXIT_FAILURE); } } // Allocate memory for an array of unsigned chars. uint8_t * allocate_ustrmem (int len) { void *tmp; if (len <= 0) { fprintf (stderr, "ERROR: Cannot allocate memory because len = %i in allocate_ustrmem().\n", len); exit (EXIT_FAILURE); } tmp = (uint8_t *) malloc (len * sizeof (uint8_t)); if (tmp != NULL) { memset (tmp, 0, len * sizeof (uint8_t)); return (tmp); } else { fprintf (stderr, "ERROR: Cannot allocate memory for array allocate_ustrmem().\n"); exit (EXIT_FAILURE); } }
the_stack_data/211079564.c
/*Program to input a single character Third Week Lab(3.2) Author; Aaron Byrne C15709609 Date; 06/10/2015*/ #include <stdio.h> main() { char ch1; char ch2; printf("Enter a first character\n"); scanf("%1s",&ch1); printf("Enter a second character\n"); scanf("1s",&ch2); printf("\n You entered %c",ch1); printf("\n You entered %c",ch2); getchar(); }//end main
the_stack_data/78232.c
#include <limits.h> #include <stdlib.h> char *itoa (int val, char *str) { char* valuestring = (char*) str; int value = val; int min_flag; char swap, *p; min_flag = 0; if (0 > value) { *valuestring++ = '-'; value = -INT_MAX> value ? min_flag = INT_MAX : -value; } p = valuestring; do { *p++ = (char)(value % 10) + '0'; value /= 10; } while (value); if (min_flag != 0) { ++*valuestring; } *p-- = '\0'; while (p > valuestring) { swap = *valuestring; *valuestring++ = *p; *p-- = swap; } return str; }
the_stack_data/3263163.c
#include <stdio.h> int main(void) { int N, t, count; scanf("%d", &N); count = 0; for(int i = 0; i < N; i++) { scanf("%d", &t); if (t > 0) count++; } printf("%d\n", count); return 0; }
the_stack_data/7473.c
// BUG: unable to handle kernel NULL pointer dereference in corrupted (2) // https://syzkaller.appspot.com/bug?id=b31b24972cbf63b9e328c9481d945d89c5d2ff50 // status:fixed // autogenerated by syzkaller (http://github.com/google/syzkaller) #define _GNU_SOURCE #include <dirent.h> #include <endian.h> #include <errno.h> #include <errno.h> #include <errno.h> #include <fcntl.h> #include <linux/futex.h> #include <linux/net.h> #include <netinet/in.h> #include <pthread.h> #include <sched.h> #include <signal.h> #include <signal.h> #include <stdarg.h> #include <stdarg.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <sys/mount.h> #include <sys/mount.h> #include <sys/prctl.h> #include <sys/prctl.h> #include <sys/resource.h> #include <sys/socket.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/time.h> #include <sys/time.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/wait.h> #include <time.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 <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 uint64_t current_time_ms() { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts)) fail("clock_gettime failed"); return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000; } 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 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 setup_cgroups() { if (mkdir("/syzcgroup", 0777)) { } if (mkdir("/syzcgroup/unified", 0777)) { } if (mount("none", "/syzcgroup/unified", "cgroup2", 0, NULL)) { } if (chmod("/syzcgroup/unified", 0777)) { } if (!write_file("/syzcgroup/unified/cgroup.subtree_control", "+cpu +memory +io +pids +rdma")) { } if (mkdir("/syzcgroup/cpu", 0777)) { } if (mount("none", "/syzcgroup/cpu", "cgroup", 0, "cpuset,cpuacct,perf_event,hugetlb")) { } if (!write_file("/syzcgroup/cpu/cgroup.clone_children", "1")) { } if (chmod("/syzcgroup/cpu", 0777)) { } if (mkdir("/syzcgroup/net", 0777)) { } if (mount("none", "/syzcgroup/net", "cgroup", 0, "net_cls,net_prio,devices,freezer")) { } if (chmod("/syzcgroup/net", 0777)) { } } static void setup_binfmt_misc() { if (!write_file("/proc/sys/fs/binfmt_misc/register", ":syz0:M:0:syz0::./file0:")) { } if (!write_file("/proc/sys/fs/binfmt_misc/register", ":syz1:M:1:yz1::./file0:POC")) { } } 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)) { } } int wait_for_loop(int pid) { if (pid < 0) fail("sandbox fork failed"); int status = 0; while (waitpid(-1, &status, __WALL) != pid) { } return WEXITSTATUS(status); } static int do_sandbox_none(void) { if (unshare(CLONE_NEWPID)) { } int pid = fork(); if (pid != 0) return wait_for_loop(pid); setup_cgroups(); setup_binfmt_misc(); sandbox_common(); if (unshare(CLONE_NEWNET)) { } loop(); doexit(1); } #define XT_TABLE_SIZE 1536 #define XT_MAX_ENTRIES 10 struct xt_counters { uint64_t pcnt, bcnt; }; struct ipt_getinfo { char name[32]; unsigned int valid_hooks; unsigned int hook_entry[5]; unsigned int underflow[5]; unsigned int num_entries; unsigned int size; }; struct ipt_get_entries { char name[32]; unsigned int size; void* entrytable[XT_TABLE_SIZE / sizeof(void*)]; }; struct ipt_replace { char name[32]; unsigned int valid_hooks; unsigned int num_entries; unsigned int size; unsigned int hook_entry[5]; unsigned int underflow[5]; unsigned int num_counters; struct xt_counters* counters; char entrytable[XT_TABLE_SIZE]; }; struct ipt_table_desc { const char* name; struct ipt_getinfo info; struct ipt_replace replace; }; static struct ipt_table_desc ipv4_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "mangle"}, {.name = "raw"}, {.name = "security"}, }; static struct ipt_table_desc ipv6_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "mangle"}, {.name = "raw"}, {.name = "security"}, }; #define IPT_BASE_CTL 64 #define IPT_SO_SET_REPLACE (IPT_BASE_CTL) #define IPT_SO_GET_INFO (IPT_BASE_CTL) #define IPT_SO_GET_ENTRIES (IPT_BASE_CTL + 1) struct arpt_getinfo { char name[32]; unsigned int valid_hooks; unsigned int hook_entry[3]; unsigned int underflow[3]; unsigned int num_entries; unsigned int size; }; struct arpt_get_entries { char name[32]; unsigned int size; void* entrytable[XT_TABLE_SIZE / sizeof(void*)]; }; struct arpt_replace { char name[32]; unsigned int valid_hooks; unsigned int num_entries; unsigned int size; unsigned int hook_entry[3]; unsigned int underflow[3]; unsigned int num_counters; struct xt_counters* counters; char entrytable[XT_TABLE_SIZE]; }; struct arpt_table_desc { const char* name; struct arpt_getinfo info; struct arpt_replace replace; }; static struct arpt_table_desc arpt_tables[] = { {.name = "filter"}, }; #define ARPT_BASE_CTL 96 #define ARPT_SO_SET_REPLACE (ARPT_BASE_CTL) #define ARPT_SO_GET_INFO (ARPT_BASE_CTL) #define ARPT_SO_GET_ENTRIES (ARPT_BASE_CTL + 1) static void checkpoint_iptables(struct ipt_table_desc* tables, int num_tables, int family, int level) { struct ipt_get_entries entries; socklen_t optlen; int fd, i; fd = socket(family, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } fail("socket(%d, SOCK_STREAM, IPPROTO_TCP)", family); } for (i = 0; i < num_tables; i++) { struct ipt_table_desc* table = &tables[i]; strcpy(table->info.name, table->name); strcpy(table->replace.name, table->name); optlen = sizeof(table->info); if (getsockopt(fd, level, IPT_SO_GET_INFO, &table->info, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } fail("getsockopt(IPT_SO_GET_INFO)"); } if (table->info.size > sizeof(table->replace.entrytable)) fail("table size is too large: %u", table->info.size); if (table->info.num_entries > XT_MAX_ENTRIES) fail("too many counters: %u", table->info.num_entries); memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + table->info.size; if (getsockopt(fd, level, IPT_SO_GET_ENTRIES, &entries, &optlen)) fail("getsockopt(IPT_SO_GET_ENTRIES)"); table->replace.valid_hooks = table->info.valid_hooks; table->replace.num_entries = table->info.num_entries; table->replace.size = table->info.size; memcpy(table->replace.hook_entry, table->info.hook_entry, sizeof(table->replace.hook_entry)); memcpy(table->replace.underflow, table->info.underflow, sizeof(table->replace.underflow)); memcpy(table->replace.entrytable, entries.entrytable, table->info.size); } close(fd); } static void reset_iptables(struct ipt_table_desc* tables, int num_tables, int family, int level) { struct xt_counters counters[XT_MAX_ENTRIES]; struct ipt_get_entries entries; struct ipt_getinfo info; socklen_t optlen; int fd, i; fd = socket(family, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } fail("socket(%d, SOCK_STREAM, IPPROTO_TCP)", family); } for (i = 0; i < num_tables; i++) { struct ipt_table_desc* table = &tables[i]; if (table->info.valid_hooks == 0) continue; memset(&info, 0, sizeof(info)); strcpy(info.name, table->name); optlen = sizeof(info); if (getsockopt(fd, level, IPT_SO_GET_INFO, &info, &optlen)) fail("getsockopt(IPT_SO_GET_INFO)"); if (memcmp(&table->info, &info, sizeof(table->info)) == 0) { memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + entries.size; if (getsockopt(fd, level, IPT_SO_GET_ENTRIES, &entries, &optlen)) fail("getsockopt(IPT_SO_GET_ENTRIES)"); if (memcmp(table->replace.entrytable, entries.entrytable, table->info.size) == 0) continue; } table->replace.num_counters = info.num_entries; table->replace.counters = counters; optlen = sizeof(table->replace) - sizeof(table->replace.entrytable) + table->replace.size; if (setsockopt(fd, level, IPT_SO_SET_REPLACE, &table->replace, optlen)) fail("setsockopt(IPT_SO_SET_REPLACE)"); } close(fd); } static void checkpoint_arptables(void) { struct arpt_get_entries entries; socklen_t optlen; unsigned i; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } fail("socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)"); } for (i = 0; i < sizeof(arpt_tables) / sizeof(arpt_tables[0]); i++) { struct arpt_table_desc* table = &arpt_tables[i]; strcpy(table->info.name, table->name); strcpy(table->replace.name, table->name); optlen = sizeof(table->info); if (getsockopt(fd, SOL_IP, ARPT_SO_GET_INFO, &table->info, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } fail("getsockopt(ARPT_SO_GET_INFO)"); } if (table->info.size > sizeof(table->replace.entrytable)) fail("table size is too large: %u", table->info.size); if (table->info.num_entries > XT_MAX_ENTRIES) fail("too many counters: %u", table->info.num_entries); memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + table->info.size; if (getsockopt(fd, SOL_IP, ARPT_SO_GET_ENTRIES, &entries, &optlen)) fail("getsockopt(ARPT_SO_GET_ENTRIES)"); table->replace.valid_hooks = table->info.valid_hooks; table->replace.num_entries = table->info.num_entries; table->replace.size = table->info.size; memcpy(table->replace.hook_entry, table->info.hook_entry, sizeof(table->replace.hook_entry)); memcpy(table->replace.underflow, table->info.underflow, sizeof(table->replace.underflow)); memcpy(table->replace.entrytable, entries.entrytable, table->info.size); } close(fd); } static void reset_arptables() { struct xt_counters counters[XT_MAX_ENTRIES]; struct arpt_get_entries entries; struct arpt_getinfo info; socklen_t optlen; unsigned i; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } fail("socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)"); } for (i = 0; i < sizeof(arpt_tables) / sizeof(arpt_tables[0]); i++) { struct arpt_table_desc* table = &arpt_tables[i]; if (table->info.valid_hooks == 0) continue; memset(&info, 0, sizeof(info)); strcpy(info.name, table->name); optlen = sizeof(info); if (getsockopt(fd, SOL_IP, ARPT_SO_GET_INFO, &info, &optlen)) fail("getsockopt(ARPT_SO_GET_INFO)"); if (memcmp(&table->info, &info, sizeof(table->info)) == 0) { memset(&entries, 0, sizeof(entries)); strcpy(entries.name, table->name); entries.size = table->info.size; optlen = sizeof(entries) - sizeof(entries.entrytable) + entries.size; if (getsockopt(fd, SOL_IP, ARPT_SO_GET_ENTRIES, &entries, &optlen)) fail("getsockopt(ARPT_SO_GET_ENTRIES)"); if (memcmp(table->replace.entrytable, entries.entrytable, table->info.size) == 0) continue; } table->replace.num_counters = info.num_entries; table->replace.counters = counters; optlen = sizeof(table->replace) - sizeof(table->replace.entrytable) + table->replace.size; if (setsockopt(fd, SOL_IP, ARPT_SO_SET_REPLACE, &table->replace, optlen)) fail("setsockopt(ARPT_SO_SET_REPLACE)"); } close(fd); } #include <linux/if.h> #include <linux/netfilter_bridge/ebtables.h> struct ebt_table_desc { const char* name; struct ebt_replace replace; char entrytable[XT_TABLE_SIZE]; }; static struct ebt_table_desc ebt_tables[] = { {.name = "filter"}, {.name = "nat"}, {.name = "broute"}, }; static void checkpoint_ebtables(void) { socklen_t optlen; unsigned i; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } fail("socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)"); } for (i = 0; i < sizeof(ebt_tables) / sizeof(ebt_tables[0]); i++) { struct ebt_table_desc* table = &ebt_tables[i]; strcpy(table->replace.name, table->name); optlen = sizeof(table->replace); if (getsockopt(fd, SOL_IP, EBT_SO_GET_INIT_INFO, &table->replace, &optlen)) { switch (errno) { case EPERM: case ENOENT: case ENOPROTOOPT: continue; } fail("getsockopt(EBT_SO_GET_INIT_INFO)"); } if (table->replace.entries_size > sizeof(table->entrytable)) fail("table size is too large: %u", table->replace.entries_size); table->replace.num_counters = 0; table->replace.entries = table->entrytable; optlen = sizeof(table->replace) + table->replace.entries_size; if (getsockopt(fd, SOL_IP, EBT_SO_GET_INIT_ENTRIES, &table->replace, &optlen)) fail("getsockopt(EBT_SO_GET_INIT_ENTRIES)"); } close(fd); } static void reset_ebtables() { struct ebt_replace replace; char entrytable[XT_TABLE_SIZE]; socklen_t optlen; unsigned i, j, h; int fd; fd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (fd == -1) { switch (errno) { case EAFNOSUPPORT: case ENOPROTOOPT: return; } fail("socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)"); } for (i = 0; i < sizeof(ebt_tables) / sizeof(ebt_tables[0]); i++) { struct ebt_table_desc* table = &ebt_tables[i]; if (table->replace.valid_hooks == 0) continue; memset(&replace, 0, sizeof(replace)); strcpy(replace.name, table->name); optlen = sizeof(replace); if (getsockopt(fd, SOL_IP, EBT_SO_GET_INFO, &replace, &optlen)) fail("getsockopt(EBT_SO_GET_INFO)"); replace.num_counters = 0; table->replace.entries = 0; for (h = 0; h < NF_BR_NUMHOOKS; h++) table->replace.hook_entry[h] = 0; if (memcmp(&table->replace, &replace, sizeof(table->replace)) == 0) { memset(&entrytable, 0, sizeof(entrytable)); replace.entries = entrytable; optlen = sizeof(replace) + replace.entries_size; if (getsockopt(fd, SOL_IP, EBT_SO_GET_ENTRIES, &replace, &optlen)) fail("getsockopt(EBT_SO_GET_ENTRIES)"); if (memcmp(table->entrytable, entrytable, replace.entries_size) == 0) continue; } for (j = 0, h = 0; h < NF_BR_NUMHOOKS; h++) { if (table->replace.valid_hooks & (1 << h)) { table->replace.hook_entry[h] = (struct ebt_entries*)table->entrytable + j; j++; } } table->replace.entries = table->entrytable; optlen = sizeof(table->replace) + table->replace.entries_size; if (setsockopt(fd, SOL_IP, EBT_SO_SET_ENTRIES, &table->replace, optlen)) fail("setsockopt(EBT_SO_SET_ENTRIES)"); } close(fd); } static void checkpoint_net_namespace(void) { checkpoint_ebtables(); checkpoint_arptables(); checkpoint_iptables(ipv4_tables, sizeof(ipv4_tables) / sizeof(ipv4_tables[0]), AF_INET, SOL_IP); checkpoint_iptables(ipv6_tables, sizeof(ipv6_tables) / sizeof(ipv6_tables[0]), AF_INET6, SOL_IPV6); } static void reset_net_namespace(void) { reset_ebtables(); reset_arptables(); reset_iptables(ipv4_tables, sizeof(ipv4_tables) / sizeof(ipv4_tables[0]), AF_INET, SOL_IP); reset_iptables(ipv6_tables, sizeof(ipv6_tables) / sizeof(ipv6_tables[0]), AF_INET6, SOL_IPV6); } static void remove_dir(const char* dir) { DIR* dp; struct dirent* ep; int iter = 0; retry: while (umount2(dir, MNT_DETACH) == 0) { } dp = opendir(dir); if (dp == NULL) { if (errno == EMFILE) { exitf("opendir(%s) failed due to NOFILE, exiting", dir); } exitf("opendir(%s) failed", dir); } while ((ep = readdir(dp))) { if (strcmp(ep->d_name, ".") == 0 || strcmp(ep->d_name, "..") == 0) continue; char filename[FILENAME_MAX]; snprintf(filename, sizeof(filename), "%s/%s", dir, ep->d_name); while (umount2(filename, MNT_DETACH) == 0) { } struct stat st; if (lstat(filename, &st)) exitf("lstat(%s) failed", filename); if (S_ISDIR(st.st_mode)) { remove_dir(filename); continue; } int i; for (i = 0;; i++) { if (unlink(filename) == 0) break; if (errno == EROFS) { break; } if (errno != EBUSY || i > 100) exitf("unlink(%s) failed", filename); if (umount2(filename, MNT_DETACH)) exitf("umount(%s) failed", filename); } } closedir(dp); int i; for (i = 0;; i++) { if (rmdir(dir) == 0) break; if (i < 100) { if (errno == EROFS) { break; } if (errno == EBUSY) { if (umount2(dir, MNT_DETACH)) exitf("umount(%s) failed", dir); continue; } if (errno == ENOTEMPTY) { if (iter < 100) { iter++; goto retry; } } } exitf("rmdir(%s) failed", dir); } } static void execute_one(); extern unsigned long long procid; static void loop() { checkpoint_net_namespace(); char cgroupdir[64]; snprintf(cgroupdir, sizeof(cgroupdir), "/syzcgroup/unified/syz%llu", procid); char cgroupdir_cpu[64]; snprintf(cgroupdir_cpu, sizeof(cgroupdir_cpu), "/syzcgroup/cpu/syz%llu", procid); char cgroupdir_net[64]; snprintf(cgroupdir_net, sizeof(cgroupdir_net), "/syzcgroup/net/syz%llu", procid); if (mkdir(cgroupdir, 0777)) { } if (mkdir(cgroupdir_cpu, 0777)) { } if (mkdir(cgroupdir_net, 0777)) { } int pid = getpid(); char procs_file[128]; snprintf(procs_file, sizeof(procs_file), "%s/cgroup.procs", cgroupdir); if (!write_file(procs_file, "%d", pid)) { } snprintf(procs_file, sizeof(procs_file), "%s/cgroup.procs", cgroupdir_cpu); if (!write_file(procs_file, "%d", pid)) { } snprintf(procs_file, sizeof(procs_file), "%s/cgroup.procs", cgroupdir_net); if (!write_file(procs_file, "%d", pid)) { } int iter; for (iter = 0;; iter++) { char cwdbuf[32]; sprintf(cwdbuf, "./%d", iter); if (mkdir(cwdbuf, 0777)) fail("failed to mkdir"); int pid = fork(); if (pid < 0) fail("clone failed"); if (pid == 0) { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); if (chdir(cwdbuf)) fail("failed to chdir"); if (symlink(cgroupdir, "./cgroup")) { } if (symlink(cgroupdir_cpu, "./cgroup.cpu")) { } if (symlink(cgroupdir_net, "./cgroup.net")) { } execute_one(); int fd; for (fd = 3; fd < 30; fd++) close(fd); doexit(0); } int status = 0; uint64_t start = current_time_ms(); for (;;) { int res = waitpid(-1, &status, __WALL | WNOHANG); if (res == pid) { break; } usleep(1000); if (current_time_ms() - start < 5 * 1000) continue; kill(-pid, SIGKILL); kill(pid, SIGKILL); while (waitpid(-1, &status, __WALL) != pid) { } break; } remove_dir(cwdbuf); reset_net_namespace(); } } 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 (__atomic_load_n(&running, __ATOMIC_RELAXED)) usleep((call == num_calls - 1) ? 10000 : 1000); break; } } } } #ifndef __NR_bpf #define __NR_bpf 321 #endif uint64_t r[1] = {0xffffffffffffffff}; unsigned long long procid; void execute_call(int call) { long res; switch (call) { case 0: syscall(__NR_socketpair, 0, 0, 0, 0x20000140); break; case 1: syscall(__NR_socket, 0xa, 1, 0); break; case 2: *(uint32_t*)0x20000280 = 0xf; *(uint32_t*)0x20000284 = 4; *(uint32_t*)0x20000288 = 4; *(uint32_t*)0x2000028c = 0x70; *(uint32_t*)0x20000290 = 0; *(uint32_t*)0x20000294 = -1; *(uint32_t*)0x20000298 = 0; *(uint8_t*)0x2000029c = 0; *(uint8_t*)0x2000029d = 0; *(uint8_t*)0x2000029e = 0; *(uint8_t*)0x2000029f = 0; *(uint8_t*)0x200002a0 = 0; *(uint8_t*)0x200002a1 = 0; *(uint8_t*)0x200002a2 = 0; *(uint8_t*)0x200002a3 = 0; *(uint8_t*)0x200002a4 = 0; *(uint8_t*)0x200002a5 = 0; *(uint8_t*)0x200002a6 = 0; *(uint8_t*)0x200002a7 = 0; *(uint8_t*)0x200002a8 = 0; *(uint8_t*)0x200002a9 = 0; *(uint8_t*)0x200002aa = 0; *(uint8_t*)0x200002ab = 0; res = syscall(__NR_bpf, 0, 0x20000280, 0x2c); if (res != -1) r[0] = res; break; case 3: *(uint32_t*)0x20000180 = r[0]; *(uint64_t*)0x20000188 = 0x20000000; *(uint64_t*)0x20000190 = 0x20000140; *(uint64_t*)0x20000198 = 0; syscall(__NR_bpf, 2, 0x20000180, 0x20); break; case 4: *(uint32_t*)0x20000000 = r[0]; *(uint64_t*)0x20000008 = 0x20000000; *(uint64_t*)0x20000010 = 0x20000140; *(uint64_t*)0x20000018 = 0; syscall(__NR_bpf, 2, 0x20000000, 0x20); break; } } void execute_one() { execute(5); collide = 1; execute(5); } int main() { syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0); char* cwd = get_current_dir_name(); for (;;) { if (chdir(cwd)) fail("failed to chdir"); use_temporary_dir(); do_sandbox_none(); } }
the_stack_data/72012874.c
/* * wpa_supplicant - WPA/RSN IE and KDE processing * Copyright (c) 2003-2008, Jouni Malinen <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * Alternatively, this software may be distributed under the terms of BSD * license. * * See README and COPYING for more details. */ #ifdef ESP_SUPPLICANT #include "utils/includes.h" #include "utils/common.h" #include "rsn_supp/wpa.h" #include "common/ieee802_11_defs.h" #include "rsn_supp/wpa_ie.h" #include "rsn_supp/pmksa_cache.h" /** * wpa_parse_wpa_ie - Parse WPA/RSN IE * @wpa_ie: Pointer to WPA or RSN IE * @wpa_ie_len: Length of the WPA/RSN IE * @data: Pointer to data area for parsing results * Returns: 0 on success, -1 on failure * * Parse the contents of WPA or RSN IE and write the parsed data into data. */ int wpa_parse_wpa_ie(const u8 *wpa_ie, size_t wpa_ie_len, struct wpa_ie_data *data) { if (wpa_ie_len >= 1 && wpa_ie[0] == WLAN_EID_RSN) return wpa_parse_wpa_ie_rsn(wpa_ie, wpa_ie_len, data); else return wpa_parse_wpa_ie_wpa(wpa_ie, wpa_ie_len, data); } static int wpa_gen_wpa_ie_wpa(u8 *wpa_ie, size_t wpa_ie_len, int pairwise_cipher, int group_cipher, int key_mgmt) { u8 *pos; struct wpa_ie_hdr *hdr; if (wpa_ie_len < sizeof(*hdr) + WPA_SELECTOR_LEN + 2 + WPA_SELECTOR_LEN + 2 + WPA_SELECTOR_LEN) return -1; hdr = (struct wpa_ie_hdr *) wpa_ie; hdr->elem_id = WLAN_EID_VENDOR_SPECIFIC; RSN_SELECTOR_PUT(hdr->oui, WPA_OUI_TYPE); WPA_PUT_LE16(hdr->version, WPA_VERSION); pos = (u8 *) (hdr + 1); if (group_cipher == WPA_CIPHER_CCMP) { RSN_SELECTOR_PUT(pos, WPA_CIPHER_SUITE_CCMP); } else if (group_cipher == WPA_CIPHER_TKIP) { RSN_SELECTOR_PUT(pos, WPA_CIPHER_SUITE_TKIP); } else if (group_cipher == WPA_CIPHER_WEP104) { RSN_SELECTOR_PUT(pos, WPA_CIPHER_SUITE_WEP104); } else if (group_cipher == WPA_CIPHER_WEP40) { RSN_SELECTOR_PUT(pos, WPA_CIPHER_SUITE_WEP40); } else { wpa_printf(MSG_DEBUG, "Invalid group cipher (%d).", group_cipher); return -1; } pos += WPA_SELECTOR_LEN; *pos++ = 1; *pos++ = 0; if (pairwise_cipher == WPA_CIPHER_CCMP) { RSN_SELECTOR_PUT(pos, WPA_CIPHER_SUITE_CCMP); } else if (pairwise_cipher == WPA_CIPHER_TKIP) { RSN_SELECTOR_PUT(pos, WPA_CIPHER_SUITE_TKIP); } else if (pairwise_cipher == WPA_CIPHER_NONE) { RSN_SELECTOR_PUT(pos, WPA_CIPHER_SUITE_NONE); } else { wpa_printf(MSG_DEBUG, "Invalid pairwise cipher (%d).", pairwise_cipher); return -1; } pos += WPA_SELECTOR_LEN; *pos++ = 1; *pos++ = 0; if (key_mgmt == WPA_KEY_MGMT_IEEE8021X) { RSN_SELECTOR_PUT(pos, WPA_AUTH_KEY_MGMT_UNSPEC_802_1X); } else if (key_mgmt == WPA_KEY_MGMT_PSK) { RSN_SELECTOR_PUT(pos, WPA_AUTH_KEY_MGMT_PSK_OVER_802_1X); } else if (key_mgmt == WPA_KEY_MGMT_WPA_NONE) { RSN_SELECTOR_PUT(pos, WPA_AUTH_KEY_MGMT_NONE); } else { wpa_printf(MSG_DEBUG, "Invalid key management type (%d).", key_mgmt); return -1; } pos += WPA_SELECTOR_LEN; /* WPA Capabilities; use defaults, so no need to include it */ hdr->len = (pos - wpa_ie) - 2; WPA_ASSERT((size_t) (pos - wpa_ie) <= wpa_ie_len); return pos - wpa_ie; } static int wpa_gen_wpa_ie_rsn(u8 *rsn_ie, size_t rsn_ie_len, int pairwise_cipher, int group_cipher, int key_mgmt, int mgmt_group_cipher, struct wpa_sm *sm) { #ifndef CONFIG_NO_WPA2 u8 *pos; struct rsn_ie_hdr *hdr; u16 capab; u8 min_len = 0; if (rsn_ie_len < sizeof(*hdr) + RSN_SELECTOR_LEN + 2 + RSN_SELECTOR_LEN + 2 + RSN_SELECTOR_LEN + 2 + (sm->cur_pmksa ? 2 + PMKID_LEN : 0)) { wpa_printf(MSG_DEBUG, "RSN: Too short IE buffer (%lu bytes)", (unsigned long) rsn_ie_len); return -1; } /* For WPA2-PSK, if the RSNE in AP beacon/probe response doesn't specify the * pairwise cipher or AKM suite, the RSNE IE in association request * should only contain group cihpher suite, otherwise the WPA2 improvements * certification will fail. */ if ( (sm->ap_notify_completed_rsne == true) || (key_mgmt == WPA_KEY_MGMT_IEEE8021X) ) { min_len = sizeof(*hdr) + RSN_SELECTOR_LEN + 2 + RSN_SELECTOR_LEN + 2 + RSN_SELECTOR_LEN + 2; } else { min_len = sizeof(*hdr) + RSN_SELECTOR_LEN; } if (rsn_ie_len < min_len) { wpa_printf(MSG_DEBUG, "RSN: Too short IE buffer (%lu bytes)", (unsigned long) rsn_ie_len); } hdr = (struct rsn_ie_hdr *) rsn_ie; hdr->elem_id = WLAN_EID_RSN; WPA_PUT_LE16(hdr->version, RSN_VERSION); pos = (u8 *) (hdr + 1); if (group_cipher == WPA_CIPHER_CCMP) { RSN_SELECTOR_PUT(pos, RSN_CIPHER_SUITE_CCMP); } else if (group_cipher == WPA_CIPHER_TKIP) { RSN_SELECTOR_PUT(pos, RSN_CIPHER_SUITE_TKIP); } else if (group_cipher == WPA_CIPHER_WEP104) { RSN_SELECTOR_PUT(pos, RSN_CIPHER_SUITE_WEP104); } else if (group_cipher == WPA_CIPHER_WEP40) { RSN_SELECTOR_PUT(pos, RSN_CIPHER_SUITE_WEP40); } else { wpa_printf(MSG_DEBUG, "Invalid group cipher (%d).", group_cipher); return -1; } pos += RSN_SELECTOR_LEN; if ( (sm->ap_notify_completed_rsne == false) && (key_mgmt != WPA_KEY_MGMT_IEEE8021X) ) { hdr->len = (pos - rsn_ie) - 2; return (pos - rsn_ie); } *pos++ = 1; *pos++ = 0; if (pairwise_cipher == WPA_CIPHER_CCMP) { RSN_SELECTOR_PUT(pos, RSN_CIPHER_SUITE_CCMP); } else if (pairwise_cipher == WPA_CIPHER_TKIP) { RSN_SELECTOR_PUT(pos, RSN_CIPHER_SUITE_TKIP); } else if (pairwise_cipher == WPA_CIPHER_NONE) { RSN_SELECTOR_PUT(pos, RSN_CIPHER_SUITE_NONE); } else { wpa_printf(MSG_DEBUG, "Invalid pairwise cipher (%d).", pairwise_cipher); return -1; } pos += RSN_SELECTOR_LEN; *pos++ = 1; *pos++ = 0; if (key_mgmt == WPA_KEY_MGMT_IEEE8021X) { RSN_SELECTOR_PUT(pos, RSN_AUTH_KEY_MGMT_UNSPEC_802_1X); } else if (key_mgmt == WPA_KEY_MGMT_PSK) { RSN_SELECTOR_PUT(pos, RSN_AUTH_KEY_MGMT_PSK_OVER_802_1X); #ifdef CONFIG_IEEE80211R } else if (key_mgmt == WPA_KEY_MGMT_FT_IEEE8021X) { RSN_SELECTOR_PUT(pos, RSN_AUTH_KEY_MGMT_FT_802_1X); } else if (key_mgmt == WPA_KEY_MGMT_FT_PSK) { RSN_SELECTOR_PUT(pos, RSN_AUTH_KEY_MGMT_FT_PSK); #endif /* CONFIG_IEEE80211R */ #ifdef CONFIG_IEEE80211W } else if (key_mgmt == WPA_KEY_MGMT_IEEE8021X_SHA256) { RSN_SELECTOR_PUT(pos, RSN_AUTH_KEY_MGMT_802_1X_SHA256); } else if (key_mgmt == WPA_KEY_MGMT_PSK_SHA256) { RSN_SELECTOR_PUT(pos, RSN_AUTH_KEY_MGMT_PSK_SHA256); #endif /* CONFIG_IEEE80211W */ #ifdef CONFIG_WPA3_SAE } else if (key_mgmt == WPA_KEY_MGMT_SAE) { RSN_SELECTOR_PUT(pos, RSN_AUTH_KEY_MGMT_SAE); #endif /* CONFIG_WPA3_SAE */ } else { wpa_printf(MSG_DEBUG, "Invalid key management type (%d).", key_mgmt); return -1; } pos += RSN_SELECTOR_LEN; /* RSN Capabilities */ capab = 0; #ifdef CONFIG_IEEE80211W if (sm->pmf_cfg.capable) { capab |= WPA_CAPABILITY_MFPC; if (sm->pmf_cfg.required || key_mgmt == WPA_KEY_MGMT_SAE) { capab |= WPA_CAPABILITY_MFPR; } } #endif /* CONFIG_IEEE80211W */ WPA_PUT_LE16(pos, capab); pos += 2; if (sm->cur_pmksa) { /* PMKID Count (2 octets, little endian) */ *pos++ = 1; *pos++ = 0; /* PMKID */ os_memcpy(pos, sm->cur_pmksa->pmkid, PMKID_LEN); pos += PMKID_LEN; } #ifdef CONFIG_IEEE80211W if (mgmt_group_cipher == WPA_CIPHER_AES_128_CMAC) { if (!sm->cur_pmksa) { /* 0 PMKID Count */ WPA_PUT_LE16(pos, 0); pos += 2; } /* Management Group Cipher Suite */ RSN_SELECTOR_PUT(pos, RSN_CIPHER_SUITE_AES_128_CMAC); pos += RSN_SELECTOR_LEN; } #endif /* CONFIG_IEEE80211W */ hdr->len = (pos - rsn_ie) - 2; WPA_ASSERT((size_t) (pos - rsn_ie) <= rsn_ie_len); return pos - rsn_ie; #else /* CONFIG_NO_WPA2 */ return -1; #endif /* CONFIG_NO_WPA2 */ } /** * wpa_gen_wpa_ie - Generate WPA/RSN IE based on current security policy * @sm: Pointer to WPA state machine data from wpa_sm_init() * @wpa_ie: Pointer to memory area for the generated WPA/RSN IE * @wpa_ie_len: Maximum length of the generated WPA/RSN IE * Returns: Length of the generated WPA/RSN IE or -1 on failure */ int wpa_gen_wpa_ie(struct wpa_sm *sm, u8 *wpa_ie, size_t wpa_ie_len) { if (sm->proto == WPA_PROTO_RSN) return wpa_gen_wpa_ie_rsn(wpa_ie, wpa_ie_len, sm->pairwise_cipher, sm->group_cipher, sm->key_mgmt, sm->mgmt_group_cipher, sm); else return wpa_gen_wpa_ie_wpa(wpa_ie, wpa_ie_len, sm->pairwise_cipher, sm->group_cipher, sm->key_mgmt); } /** * wpa_parse_generic - Parse EAPOL-Key Key Data Generic IEs * @pos: Pointer to the IE header * @end: Pointer to the end of the Key Data buffer * @ie: Pointer to parsed IE data * Returns: 0 on success, 1 if end mark is found, -1 on failure */ static int wpa_parse_generic(const u8 *pos, const u8 *end, struct wpa_eapol_ie_parse *ie) { if (pos[1] == 0) return 1; if (pos[1] >= 6 && RSN_SELECTOR_GET(pos + 2) == WPA_OUI_TYPE && pos[2 + WPA_SELECTOR_LEN] == 1 && pos[2 + WPA_SELECTOR_LEN + 1] == 0) { ie->wpa_ie = pos; ie->wpa_ie_len = pos[1] + 2; wpa_hexdump(MSG_DEBUG, "WPA: WPA IE in EAPOL-Key", ie->wpa_ie, ie->wpa_ie_len); return 0; } if (pos + 1 + RSN_SELECTOR_LEN < end && pos[1] >= RSN_SELECTOR_LEN + PMKID_LEN && RSN_SELECTOR_GET(pos + 2) == RSN_KEY_DATA_PMKID) { ie->pmkid = pos + 2 + RSN_SELECTOR_LEN; wpa_hexdump(MSG_DEBUG, "WPA: PMKID in EAPOL-Key", pos, pos[1] + 2); return 0; } if (pos[1] > RSN_SELECTOR_LEN + 2 && RSN_SELECTOR_GET(pos + 2) == RSN_KEY_DATA_GROUPKEY) { ie->gtk = pos + 2 + RSN_SELECTOR_LEN; ie->gtk_len = pos[1] - RSN_SELECTOR_LEN; wpa_hexdump(MSG_DEBUG, "WPA: GTK in EAPOL-Key", pos, pos[1] + 2); return 0; } if (pos[1] > RSN_SELECTOR_LEN + 2 && RSN_SELECTOR_GET(pos + 2) == RSN_KEY_DATA_MAC_ADDR) { ie->mac_addr = pos + 2 + RSN_SELECTOR_LEN; ie->mac_addr_len = pos[1] - RSN_SELECTOR_LEN; wpa_hexdump(MSG_DEBUG, "WPA: MAC Address in EAPOL-Key", pos, pos[1] + 2); return 0; } #ifdef CONFIG_IEEE80211W if (pos[1] > RSN_SELECTOR_LEN + 2 && RSN_SELECTOR_GET(pos + 2) == RSN_KEY_DATA_IGTK) { ie->igtk = pos + 2 + RSN_SELECTOR_LEN; ie->igtk_len = pos[1] - RSN_SELECTOR_LEN; wpa_hexdump(MSG_DEBUG, "WPA: IGTK in EAPOL-Key", pos, pos[1] + 2); return 0; } #endif return 0; } /** * wpa_supplicant_parse_ies - Parse EAPOL-Key Key Data IEs * @buf: Pointer to the Key Data buffer * @len: Key Data Length * @ie: Pointer to parsed IE data * Returns: 0 on success, -1 on failure */ int wpa_supplicant_parse_ies(const u8 *buf, size_t len, struct wpa_eapol_ie_parse *ie) { const u8 *pos, *end; int ret = 0; memset(ie, 0, sizeof(*ie)); for (pos = buf, end = pos + len; pos + 1 < end; pos += 2 + pos[1]) { if (pos[0] == 0xdd && ((pos == buf + len - 1) || pos[1] == 0)) { /* Ignore padding */ break; } if (pos + 2 + pos[1] > end) { #ifdef DEBUG_PRINT wpa_printf(MSG_DEBUG, "WPA: EAPOL-Key Key Data " "underflow (ie=%d len=%d pos=%d)", pos[0], pos[1], (int) (pos - buf)); #endif wpa_hexdump(MSG_DEBUG, "WPA: Key Data", buf, len); ret = -1; break; } if (*pos == WLAN_EID_RSN) { ie->rsn_ie = pos; ie->rsn_ie_len = pos[1] + 2; wpa_hexdump(MSG_DEBUG, "WPA: RSN IE in EAPOL-Key", ie->rsn_ie, ie->rsn_ie_len); } else if (*pos == WLAN_EID_VENDOR_SPECIFIC) { ret = wpa_parse_generic(pos, end, ie); if (ret < 0) break; if (ret > 0) { ret = 0; break; } } else { wpa_hexdump(MSG_DEBUG, "WPA: Unrecognized EAPOL-Key " "Key Data IE", pos, 2 + pos[1]); } } return ret; } #endif // ESP_SUPPLICANT
the_stack_data/35265.c
#include <stdio.h> int main() { char a[4]; fgets(a, 4, stdin); printf("a = %s\n", a); return 0; }
the_stack_data/12523.c
char *convertToTitle(int n) { int i = 0; char *ret = (char *)malloc(sizeof(char) * 15); i = 14; ret[i--] = '\0'; while(n){ ret[i--] = (n-1) % 26 + 'A'; n = (n-1)/26; } return ret+i+1; }
the_stack_data/140766067.c
/* * $Id: sys_semop.c,v 1.00 2021-02-02 17:36:42 clib2devs Exp $ */ #ifdef HAVE_SYSV #ifndef _SHM_HEADERS_H #include "shm_headers.h" #endif /* _SHM_HEADERS_H */ int _semop(int semid, const struct sembuf *ops, int nops) { DECLARE_SYSVYBASE(); int ret = -1; if (__global_clib2->haveShm) { ret = semop(semid, ops, nops); if (ret < 0) { __set_errno(GetIPCErr()); } } else { __set_errno(ENOSYS); } return ret; } #endif
the_stack_data/633357.c
#include <stdio.h> #define N 10 int main() { int a[N],arr1[N], arr2[N],pos,i,k1=0,k2=0; printf("Enter %d integer numbers\n",N); for(i=0;i<N;i++) { printf("Nr %d: ",i+1); scanf("%d",&a[i]); } printf("Enter the position to split the array into Two\n"); scanf("%d",&pos); for(i=0;i<N;i++) { if(i<pos) arr1[k1++]=a[i]; else arr2[k2++]=a[i]; } printf("\nElement of first array ->> arr1[%d]\n",k1); for(i=0;i<k1;i++) { printf("%d\t", arr1[i]); } printf("\nElement of seond array ->>arr2[%d]\n",k2); for(i=0;i<k2;i++) { printf("%d\t", arr2[i]); } return 0; }
the_stack_data/87638600.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #define MAXLINES 5000 char *lineptr[MAXLINES]; int readlines(char *lineptr[], int nlines); void writelines(char *lineptr[], int nlines, int reverse); void q_sort(void *lineptr[], int left, int right, int (*comp)(void *, void *)); int numcmp(char *, char *); int strfcmp(char *, char*); int strdcmp(char *, char *); int strdfcmp(char *, char *); int pos1 = 0; int pos2 = 0; main(int argc, char *argv[]) { int nlines; int numeric = 0; int reverse = 0; int fold = 0; int dir = 0; while (--argc > 0 && (*++argv)[0] == '-') { int c; while (c = *++argv[0]) switch (c) { case 'n': numeric = 1; break; case 'r': reverse = 1; break; case 'f': fold = 1; break; case 'd': dir = 1; break; default: printf("Illegal option: %c\n", c); break; } } if (argc > 0 && isdigit(*argv[0]) ) { pos1 = atoi(*argv); --argc; ++argv; } if (argc > 0 && isdigit(*argv[0]) ) { pos2 = atoi(*argv); --argc; ++argv; } if (argc != 0) { printf("Usage: sort -n -r -f [begin] [end]\n"); return 1; } if (pos1 > pos2) { printf("Usage: sort -n -r -f [begin] [end]\n"); printf("begin must not be greater than end\n"); return 1; } printf(numeric ? "Numerical sort\n" : "Lexicographic sort\n"); printf(reverse ? "Reverse sort\n" : "Normal sort\n"); printf(fold ? "Case insensitive\n" : "Case sensitive\n"); printf(dir ? "Directory order\n" : ""); if ((nlines = readlines(lineptr, MAXLINES)) > 0) { if (numeric) q_sort((void **) lineptr, 0, nlines - 1, (int (*)(void *, void *)) numcmp); else if (dir) if (fold) q_sort((void **) lineptr, 0, nlines - 1, (int (*)(void *, void *)) strdfcmp); else q_sort((void **) lineptr, 0, nlines - 1, (int (*)(void *, void *)) strdcmp); else if (fold) q_sort((void **) lineptr, 0, nlines - 1, (int (*)(void *, void *)) strfcmp); else q_sort((void **) lineptr, 0, nlines - 1, (int (*)(void *, void *)) strcmp); writelines(lineptr, nlines, reverse); return 0; } else { printf("input too big to sort\n"); return 1; } } void q_sort(void *v[], int left, int right, int (*comp)(void *, void *)) { int i, last; void swap(void *v[], int, int); if (left >= right) return; swap(v, left, (left + right) / 2); last = left; for (i = left + 1; i <= right; i++) if ((*comp)(v[i], v[left]) < 0) swap(v, ++last, i); swap(v, left, last); q_sort(v, left, last - 1, comp); q_sort(v, last + 1, right, comp); } void substring(char *s, char *t) { int i,j,len; len = strlen(s); if (pos2 > 0 && pos2 < len) len = pos2; if (pos2 > 0 && len < pos2) printf("error: string %s is too short\n", s); for (j=0, i=pos1; i<len; i++, j++) t[j] = s[i]; t[j] = '\0'; } int strdcmp(char *s1, char *s2) { int i, j, endpos; char a, b; i = j = pos1; if (pos2 > 0) endpos = pos2; else if ( (endpos = strlen(s1)) > strlen(s2) ) endpos = strlen(s2); do { while (i < endpos && !isalnum(*s1) && *s1 != ' ' && *s1 != '\0') s1++; while (j < endpos && !isalnum(*s2) && *s2 != ' ' && *s2 != '\0') s2++; if (i < endpos && j < endpos) { a = *s1; s1++; b = *s2; s2++; if (a == b && a == '\0') return 0; } } while (a == b && i < endpos && j < endpos); return a - b; } int strdfcmp(char *s1, char *s2) { int i, j, endpos; char a, b; i = j = pos1; if (pos2 > 0) endpos = pos2; else if ( (endpos = strlen(s1)) > strlen(s2) ) endpos = strlen(s2); do { while (i < endpos && !isalnum(*s1) && *s1 != ' ' && *s1 != '\0') s1++; while (j < endpos && !isalnum(*s2) && *s2 != ' ' && *s2 != '\0') s2++; if (i < endpos && j < endpos) { a = tolower(*s1); s1++; b = tolower(*s2); s2++; if (a == b && a == '\0') return 0; } } while (a == b && i < endpos && j < endpos); return a - b; } int strfcmp(char *s1, char *s2) { int i, j, endpos; i = j = pos1; if (pos2 > 0) endpos = pos2; else if ( (endpos = strlen(s1)) > strlen(s2) ) endpos = strlen(s2); for ( ; tolower(s1[i]) == tolower(s2[j]) && i < endpos && j < endpos; i++, j++) if (s1[i] == '\0') return 0; return tolower(s1[i])-tolower(s2[j]); } #define MAXSTR 100 int numcmp(char *s1, char *s2) { double v1, v2; char str[MAXSTR]; substring(s1, str); v1 = atof(str); substring(s2, str); v2 = atof(str); if (v1 < v2) return -1; else if (v1 > v2) return 1; else return 0; } void swap(void *v[], int i, int j) { void *temp; temp = v[i]; v[i] = v[j]; v[j] = temp; } #define MAXLEN 1000 int get_line(char line[], int maxline); char *alloc(int); int readlines(char *lineptr[], int maxlines) { int len, nlines; char *p, line[MAXLEN]; nlines = 0; while ((len = get_line(line, MAXLEN)) > 0) if (nlines >= MAXLINES || (p = alloc(len)) == NULL) return -1; else { line[len - 1] = '\0'; strcpy(p, line); lineptr[nlines++] = p; } return nlines; } void writelines(char * lineptr[], int nlines, int reverse) { int i; if (reverse) for (i = nlines-1; i >= 0; i--) printf("%s\n", lineptr[i]); else for (i = 0; i < nlines; i++) printf("%s\n", lineptr[i]); } int get_line(char s[], int lim) { int c, i; for (i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; ++i) s[i] = c; if (c == '\n') s[i++] = c; s[i] = '\0'; return i; } #define ALLOCSIZE 10000 static char allocbuf[ALLOCSIZE]; static char *allocp = allocbuf; char *alloc(int n) { if (allocbuf + ALLOCSIZE - allocp >= n) { allocp += n; return allocp - n; } else return 0; } void afree(char *p) { if (p >= allocbuf && p < allocbuf + ALLOCSIZE) allocp = p; }
the_stack_data/5920.c
// use-def elimination should have no effects // same than use_def_elim13 but declaration with init #include <stdlib.h> int use_def_elim13b_graph() { int r=0; if (rand()) r = 1; if (rand()) r = 0; return r; }
the_stack_data/6387470.c
struct complex { float real, imag; }; c_div(c, a, b) struct complex *a, *b, *c; { double ratio, den; double abr, abi; if( (abr = b->real) < 0.) abr = - abr; if( (abi = b->imag) < 0.) abi = - abi; if( abr <= abi ) { if(abi == 0) abort(); /* fatal("complex division by zero"); */ ratio = b->real / b->imag ; den = b->imag * (1 + ratio*ratio); c->real = (a->real*ratio + a->imag) / den; c->imag = (a->imag*ratio - a->real) / den; } else { ratio = b->imag / b->real ; den = b->real * (1 + ratio*ratio); c->real = (a->real + a->imag*ratio) / den; c->imag = (a->imag - a->real*ratio) / den; } }
the_stack_data/473105.c
#include<stdio.h> int main(void){ int d[10],v[3],sum,ans,i,a,b; while(1){ for(i=sum=0;i<10;i++){ if(scanf("%d,",&d[i])==EOF)return 0; sum+=d[i]; } scanf("%d,%d",&v[1],&v[2]); ans=sum*v[2]/(v[2]+v[1]); for(i=9;i>=0;i--){ ans-=d[i]; if(ans<0){ printf("%d\n",i+1); break; } } } return 0; }
the_stack_data/159515146.c
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <event.h> #include <unistd.h> #include <netinet/in.h> #include <sys/socket.h> #include <string.h> #include <fcntl.h> typedef struct sockaddr * SA; struct event_base *main_base; void str_echo(int fd, short event, void *arg) { char buf[100]; int n; n = read(fd, buf, 100); fputs("a socket has come\n", stdout); write(fd, buf, n); if (n < 0) { return ; } return ; } void call_accept(int fd, short event, void *arg) { printf("come in a new accept\n"); struct sockaddr_in cliaddr; socklen_t clilen; int connfd; connfd = accept(fd, (struct sockaddr *) &cliaddr, &clilen); printf("accept from cliaddr\n"); char buf[100]; // read(fd, buf, 100); //str_echo(connfd); // printf("%d\n", (void *)base); // struct event read_ev; // //fcntl(connfd, F_SETFL, O_NONBLOCK); // event_set(&read_ev, connfd, EV_READ, str_echo, &read_ev); // //event_base_set(main_base, &read_ev); // event_add(&read_ev, NULL); // event_base_loop(base, 0); } int main() { int listenfd, connfd; struct sockaddr_in cliaddr, servaddr; socklen_t clilen; listenfd = socket(AF_INET, SOCK_STREAM, 0); memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(9877); bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr)); listen(listenfd, 10); main_base = event_init(); struct event ev; event_set(&ev, listenfd, EV_READ | EV_PERSIST, call_accept, &ev); //event_base_set(main_base, &ev); event_add(&ev, NULL); event_base_loop(main_base, 0); printf("block before accept\n"); printf("after event_dispatch\n"); return 0; }
the_stack_data/90765386.c
/* * initialization of array belong to static storage class (static variable with * block scope, external linkage and internal linkage): * * If you don't initialize an array, its elements will be set to 0. * * initialization of array belong to automatic storage class: * * If you don’t initialize an array at all, its elements, like * uninitialized ordinary variables, get garbage values, but if you * partially initialize an array, the remaining elements are set to 0. */ int arr7[7]; // result is: {0, 0, 0, 0, 0, 0, 0} static int arr8[7]; // result is: {0, 0, 0, 0, 0, 0, 0} int main(void) { static int arr9[7]; // result is: {0, 0, 0, 0, 0, 0, 0} /* traditional initializers (ANSI C and later) */ int arr1[7] = {0, 1, 2, 3, 4, 5, 6}; // initialize all elements int arr2[7] = {0, 1, 2, 3}; // initialize paritcal elements, result is: {0, 1, 2, 3, 0, 0, 0} /* designated initializers (C99 and later) */ int arr3[7] = {[4] = 5, 6}; // result is: {0, 0, 0, 0, 5, 6, 0} int arr4[7] = {0, 1, [4] = 5, [0] = 9}; // result is: {9, 1, 0, 0, 5, 0, 0} /* initialize by omitting size */ int arr5[] = {0, 1, 2, 3, 4, 5, 6}; // same as: arr5[7] = {0, 1, 2, 3, 4, 5, 6}; int arr6[] = {0, [3]=4, 5}; // result is: {0, 0, 0, 4, 5} #if 0 #include <stdio.h> for (int i = 0; i < 7; i++) printf("%d\n", arr9[i]); #endif return 0; }
the_stack_data/122698.c
/* { dg-do compile } */ /* { dg-require-effective-target arm_eabi } */ /* { dg-options "-O2" } */ typedef struct { volatile unsigned long a:8; volatile unsigned long b:8; volatile unsigned long c:16; } BitStruct; BitStruct bits; unsigned long foo () { return bits.b; } /* { dg-final { scan-assembler "ldr\[\\t \]+\[^\n\]*,\[\\t \]*\\\[\[^\n\]*\\\]" } } */
the_stack_data/48575085.c
#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int i,j; int b[100001], a[100001] ={0}; int n,t,m; scanf("%d",&n); int x =1; for (i=0;i<n;i++){ scanf("%d",&t); a[t]++; } for (i=100000;i>0;i--){ if (a[i]!=0){ b[x] = i; x++; } } scanf("%d",&m); printf ("%d %d",b[m],a[b[m]]); return 0; }
the_stack_data/123510.c
/* { dg-do run { target i?86-*-* x86_64-*-* } } */ /* { dg-options "-O -fgcse -fno-split-wide-types" } */ extern void abort(void); typedef unsigned short int uint16_t; typedef unsigned int uint32_t; typedef unsigned long long uint64_t; typedef struct { uint16_t thread; uint16_t phase; } s32; typedef union { uint32_t i; s32 s; } u32; typedef union { uint64_t i; u32 u; } u64; static __attribute__((noinline)) void foo(int val) { u64 data; uint32_t thread; data.u.i = 0x10000L; thread = data.u.s.thread; if (val) abort (); if (thread) abort (); } int main(void) { foo (0); return 0; }
the_stack_data/192329430.c
// Copyright (C) 2009-2014 Free Software Foundation, Inc. // Written by Rafael Avila de Espindola <[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. int a = -1; extern int t1(int); int t1(int b) { return a + b; }
the_stack_data/104256.c
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { FILE *arq; char string[100]; arq = fopen("arquivo2.txt", "w"); if (arq == NULL) { printf("Erro na abertura do arquivo\n"); system("pause"); exit(1); } printf("Entre com a string a ser gravada no arquivo: "); gets(string); //Grava a string, caractere a caractere for (int i = 0; i < strlen(string); i++) { fputc(string[i], arq); } fflush(arq); fclose(arq); system("pause"); return 0; }
the_stack_data/363742.c
/**************************************************************************** * libc/math/lib_fmodf.c * * This file is a part of NuttX: * * Copyright (C) 2012 Gregory Nutt. All rights reserved. * Ported by: Darcy Gong * * It derives from the Rhombs OS math library by Nick Johnson which has * a compatibile, MIT-style license: * * Copyright (C) 2009-2011 Nick Johnson <nickbjohnson4224 at gmail.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <math.h> /**************************************************************************** * Public Functions ****************************************************************************/ float fmodf(float x, float div) { float n0; x /= div; x = modff(x, &n0); x *= div; return x; }
the_stack_data/231393046.c
/*- * Copyright (c) 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of the University 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 REGENTS 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 REGENTS 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. * * @(#)confstr.c 8.1 (Berkeley) 6/4/93 * $FreeBSD: src/lib/libc/gen/confstr.c,v 1.10 2007/01/09 00:27:53 imp Exp $ */ #include <sys/param.h> #include <errno.h> #include <limits.h> #include <paths.h> #include <string.h> #include <unistd.h> size_t confstr(int name, char *buf, size_t len) { const char *p; const char UPE[] = "unsupported programming environment"; switch (name) { case _CS_PATH: p = _PATH_STDPATH; goto docopy; /* * POSIX/SUS ``Programming Environments'' stuff * * We don't support more than one programming environment * on any platform (yet), so we just return the empty * string for the environment we are compiled for, * and the string "unsupported programming environment" * for anything else. (The Standard says that if these * values are used on a system which does not support * this environment -- determined via sysconf() -- then * the value we return is unspecified. So, we return * something which will cause obvious breakage.) */ case _CS_POSIX_V6_ILP32_OFF32_CFLAGS: case _CS_POSIX_V6_ILP32_OFF32_LDFLAGS: case _CS_POSIX_V6_ILP32_OFF32_LIBS: case _CS_POSIX_V6_LPBIG_OFFBIG_CFLAGS: case _CS_POSIX_V6_LPBIG_OFFBIG_LDFLAGS: case _CS_POSIX_V6_LPBIG_OFFBIG_LIBS: case _CS_POSIX_V7_ILP32_OFF32_CFLAGS: case _CS_POSIX_V7_ILP32_OFF32_LDFLAGS: case _CS_POSIX_V7_ILP32_OFF32_LIBS: case _CS_POSIX_V7_LPBIG_OFFBIG_CFLAGS: case _CS_POSIX_V7_LPBIG_OFFBIG_LDFLAGS: case _CS_POSIX_V7_LPBIG_OFFBIG_LIBS: /* * These two environments are never supported. */ p = UPE; goto docopy; case _CS_POSIX_V6_ILP32_OFFBIG_CFLAGS: case _CS_POSIX_V6_ILP32_OFFBIG_LDFLAGS: case _CS_POSIX_V6_ILP32_OFFBIG_LIBS: case _CS_POSIX_V7_ILP32_OFFBIG_CFLAGS: case _CS_POSIX_V7_ILP32_OFFBIG_LDFLAGS: case _CS_POSIX_V7_ILP32_OFFBIG_LIBS: if (sizeof(long) * CHAR_BIT == 32 && sizeof(off_t) > sizeof(long)) p = ""; else p = UPE; goto docopy; case _CS_POSIX_V6_LP64_OFF64_CFLAGS: case _CS_POSIX_V6_LP64_OFF64_LDFLAGS: case _CS_POSIX_V6_LP64_OFF64_LIBS: case _CS_POSIX_V7_LP64_OFF64_CFLAGS: case _CS_POSIX_V7_LP64_OFF64_LDFLAGS: case _CS_POSIX_V7_LP64_OFF64_LIBS: if (sizeof(long) * CHAR_BIT >= 64 && sizeof(void *) * CHAR_BIT >= 64 && sizeof(int) * CHAR_BIT >= 32 && sizeof(off_t) >= sizeof(long)) p = ""; else p = UPE; goto docopy; case _CS_POSIX_V6_WIDTH_RESTRICTED_ENVS: /* XXX - should have more complete coverage */ if (sizeof(long) * CHAR_BIT >= 64) p = "_POSIX_V6_LP64_OFF64"; else p = "_POSIX_V6_ILP32_OFFBIG"; goto docopy; case _CS_POSIX_V7_WIDTH_RESTRICTED_ENVS: /* XXX - should have more complete coverage */ if (sizeof(long) * CHAR_BIT >= 64) p = "_POSIX_V7_LP64_OFF64"; else p = "_POSIX_V7_ILP32_OFFBIG"; goto docopy; case _CS_V6_ENV: case _CS_V7_ENV: p = ""; goto docopy; docopy: if (len != 0 && buf != NULL) strlcpy(buf, p, len); return (strlen(p) + 1); default: errno = EINVAL; return (0); } /* NOTREACHED */ }
the_stack_data/57948943.c
#include <stdio.h> #include <stdlib.h> struct node { int data; struct node *next; }; struct node * getnode(){ struct node * t = (struct node *)malloc(sizeof(struct node)); t -> next = NULL; return t; } void add_node( struct node ** head, int item ){ if ( *head == NULL ){ struct node * k = getnode(); k -> data = item; k -> next = NULL; *head = k; } else { struct node *t = *head; while ( t -> next != NULL ){ t = t-> next; } struct node *newnode = getnode(); newnode -> data = item; newnode -> next = NULL; t -> next = newnode; } } struct node * head_g = NULL; void reverse_linklist_recursive(struct node *prev, struct node *curr){ if (curr == NULL){ head_g = prev; return; } else { reverse_linklist_recursive(curr, curr->next); curr -> next = prev; } } void prt_ll( struct node * head ){ struct node *t = head; while (t != NULL){ printf("%d\t", t -> data); t = t-> next; } printf("\n"); } void main(){ int n; printf("\nEnter no. items in linklist\n"); scanf("%d", &n); int item_1, item_2; struct node *head = NULL; printf("\nEnter elements in insert in linklist\n"); for (int i = 0; i < n; i++){ int data; scanf("%d", &data); add_node(&head, data); } prt_ll(head); reverse_linklist_recursive(NULL, head); prt_ll(head_g); }
the_stack_data/1232028.c
#include <stdio.h> #include <string.h> #include <stdlib.h> /* Functie generica pentru calcularea valorii maxime dintr-un array. n este dimensiunea array-ului element_size este dimensiunea unui element din array Se va parcurge vectorul arr, iar la fiecare iteratie sa va verifica daca functia compare intoarce 1, caz in care elementul curent va fi si cel maxim. Pentru a folosi corect aritmetica pe pointeri vom inmulti indexul curent din parcurgere cu dimensiunea unui element. Astfel, pentru accesarea elementului curent avem: void *cur_element = (char *)arr + index * element_size; */ void *find_max(void *arr, int n, int element_size, int (*compare)(const void *, const void *)) { void *max_elem = arr; return max_elem; } /* a si b sunt doi pointeri la void, dar se specifica in enunt ca datele de la acele adrese sunt de tip int, asadar trebuie castati. Functia returneaza 1 daca valorea de la adresa lui a este mai mare decat cea de la adresa lui b, in caz contrar returneaza 0. */ int compare(const void *a, const void *b); /* Se citeste de la tastatura un vector si se cere sa se afle elementul maxim folosind functia find_max. Rezultatul functiei find_max trebuie cast la int, spre exemplu: int *res = (*int) find_max(...); */ int main() { int n; scanf("%d", &n); int *arr = malloc(n * sizeof(*arr)); for (int i = 0 ; i < n; ++i) scanf("%d", &arr[i]); free(arr); return 0; }
the_stack_data/70816.c
/* { dg-do compile } */ /* { dg-options "-flive-range-shrinkage" } */ /* { dg-additional-options "-march=amdfam10" { target { i?86-*-* x86_64-*-* } } } */ struct S { int n; }; int foo (struct S s, double a) { return s.n * a; }
the_stack_data/103265409.c
#include <stdio.h> int main(void){ char c; int i = 0, j = 0; printf("Podaj wyrazy oddzielone spacja:\n"); while(c = getchar()){ if(c == '#'){ while(((c = getchar()) != ' ') && (c != '\n')){ j *= 10; j += c - '0'; //0 1 2 ... 9 //0 -> 70, 1 -> 71 //'1' -> 1, '1' - '0' = 1, '1' - '0' = 71 - 70 = 1 } if(i != j){ printf("BLAD\n"); break; } i = j = 0; } putchar(c); if(c == '\n') break; if(c != ' ') ++i; } return 0; }
the_stack_data/960.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_isalpha.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ypikul <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/10/25 01:54:07 by ypikul #+# #+# */ /* Updated: 2017/10/25 01:54:08 by ypikul ### ########.fr */ /* */ /* ************************************************************************** */ int ft_isalpha(int c) { return ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ? 1024 : 0); }
the_stack_data/150144038.c
/* -*- Last-Edit: Fri Jan 29 11:13:27 1993 by Tarak S. Goradia; -*- */ /* $Log: tcas.c,v $ * Revision 1.2 1993/03/12 19:29:50 foster * Correct logic bug which didn't allow output of 2 - hf * */ #include <stdio.h> #define OLEV 600 /* in feets/minute */ #define MAXALTDIFF 600 /* max altitude difference in feet */ #define MINSEP 300 /* min separation in feet */ #define NOZCROSS 100 /* in feet */ /* variables */ typedef int bool; int Cur_Vertical_Sep; bool High_Confidence; bool Two_of_Three_Reports_Valid; int Own_Tracked_Alt; int Own_Tracked_Alt_Rate; int Other_Tracked_Alt; int Alt_Layer_Value; /* 0, 1, 2, 3 */ int Positive_RA_Alt_Thresh[4]; int Up_Separation; int Down_Separation; /* state variables */ int Other_RAC; /* NO_INTENT, DO_NOT_CLIMB, DO_NOT_DESCEND */ #define NO_INTENT 0 #define DO_NOT_CLIMB 1 #define DO_NOT_DESCEND 2 int Other_Capability; /* TCAS_TA, OTHER */ #define TCAS_TA 1 #define OTHER 2 int Climb_Inhibit; /* true/false */ #define UNRESOLVED 0 #define UPWARD_RA 1 #define DOWNWARD_RA 2 void initialize() { Positive_RA_Alt_Thresh[0] = 400; Positive_RA_Alt_Thresh[1] = 500; Positive_RA_Alt_Thresh[2] = 640; Positive_RA_Alt_Thresh[3] = 740; } int ALIM () { return Positive_RA_Alt_Thresh[Alt_Layer_Value]; } int Inhibit_Biased_Climb () { return (Climb_Inhibit ? Up_Separation + NOZCROSS : Up_Separation); } bool Non_Crossing_Biased_Climb() { int upward_preferred; int upward_crossing_situation; bool result; upward_preferred = Inhibit_Biased_Climb() > Down_Separation; if (upward_preferred) { result = !(Own_Below_Threat()) || ((Own_Below_Threat()) && (!(Down_Separation > ALIM()))); /* opertor mutation */ } else { result = Own_Above_Threat() && (Cur_Vertical_Sep >= MINSEP) && (Up_Separation >= ALIM()); } return result; } bool Non_Crossing_Biased_Descend() { int upward_preferred; int upward_crossing_situation; bool result; upward_preferred = Inhibit_Biased_Climb() > Down_Separation; if (upward_preferred) { result = Own_Below_Threat() && (Cur_Vertical_Sep >= MINSEP) && (Down_Separation >= ALIM()); } else { result = !(Own_Above_Threat()) || ((Own_Above_Threat()) && (Up_Separation >= ALIM())); } return result; } bool Own_Below_Threat() { return (Own_Tracked_Alt < Other_Tracked_Alt); } bool Own_Above_Threat() { return (Other_Tracked_Alt < Own_Tracked_Alt); } int alt_sep_test() { bool enabled, tcas_equipped, intent_not_known; bool need_upward_RA, need_downward_RA; int alt_sep; enabled = High_Confidence && (Own_Tracked_Alt_Rate <= OLEV) && (Cur_Vertical_Sep > MAXALTDIFF); tcas_equipped = Other_Capability == TCAS_TA; intent_not_known = Two_of_Three_Reports_Valid && Other_RAC == NO_INTENT; alt_sep = UNRESOLVED; if (enabled && ((tcas_equipped && intent_not_known) || !tcas_equipped)) { need_upward_RA = Non_Crossing_Biased_Climb() && Own_Below_Threat(); need_downward_RA = Non_Crossing_Biased_Descend() && Own_Above_Threat(); if (need_upward_RA && need_downward_RA) /* unreachable: requires Own_Below_Threat and Own_Above_Threat to both be true - that requires Own_Tracked_Alt < Other_Tracked_Alt and Other_Tracked_Alt < Own_Tracked_Alt, which isn't possible */ alt_sep = UNRESOLVED; else if (need_upward_RA) alt_sep = UPWARD_RA; else if (need_downward_RA) alt_sep = DOWNWARD_RA; else alt_sep = UNRESOLVED; } return alt_sep; } main(argc, argv) int argc; char *argv[]; { if(argc < 13) { fprintf(stdout, "Error: Command line arguments are\n"); fprintf(stdout, "Cur_Vertical_Sep, High_Confidence, Two_of_Three_Reports_Valid\n"); fprintf(stdout, "Own_Tracked_Alt, Own_Tracked_Alt_Rate, Other_Tracked_Alt\n"); fprintf(stdout, "Alt_Layer_Value, Up_Separation, Down_Separation\n"); fprintf(stdout, "Other_RAC, Other_Capability, Climb_Inhibit\n"); exit(1); } initialize(); Cur_Vertical_Sep = atoi(argv[1]); High_Confidence = atoi(argv[2]); Two_of_Three_Reports_Valid = atoi(argv[3]); Own_Tracked_Alt = atoi(argv[4]); Own_Tracked_Alt_Rate = atoi(argv[5]); Other_Tracked_Alt = atoi(argv[6]); Alt_Layer_Value = atoi(argv[7]); Up_Separation = atoi(argv[8]); Down_Separation = atoi(argv[9]); Other_RAC = atoi(argv[10]); Other_Capability = atoi(argv[11]); Climb_Inhibit = atoi(argv[12]); fprintf(stdout, "%d\n", alt_sep_test()); exit(0); }
the_stack_data/28262566.c
#include <stdint.h> #include <stdio.h> typedef struct person_t { uint8_t age; char name[100]; } PERSON; void printPerson(const PERSON *p) { printf("Name: %s Age: %d", p->name, p->age); } void main() { PERSON p; p.age = 23; strcpy(p.name, "William"); printPerson(&p); }
the_stack_data/98574551.c
#include <stdio.h> #include <math.h> #include <stdbool.h> double SQR(double a); double SIGN(double a, double b); double MAX(double a, double b); double MIN(double a, double b); double rf(double x, double y, double z); double rd(double x, double y, double z); double rc (double x, double y); double rj (double x, double y, double z, double p); double snippet (double phi, double ak) { double cc =0; double q =0; double s=0; s=sin(phi); cc=SQR(cos(phi)); q=(1.0-s*ak)*(1.0+s*ak); double ans = sin(phi)*(rf(cc,q,1.0)-(SQR(s*ak))*rd(cc,q,1.0)/3.0); return ans ; } double ellpi (double phi, double en, double ak){ double cc =0; double enss=0; double q=0; double s=0; s=sin(phi); enss=en*s*s; cc=SQR(cos(phi)); q=(1.0-(s*ak))*(1.0+(s*ak)); return s*(rf(cc,q,1.0)-enss*rj(cc,q,1.0,1.0+enss)/3.0); } double SQR(double a) { return a*a; } double SIGN(double a, double b){ return b >= 0 ? (a >= 0 ? a : -a) : (a >= 0 ? -a : a); } double MAX(double a, double b){ return b > a ? (b) : (a); } double MIN(double a, double b){ return b < a ? (b) : (a); } double rf(double x, double y, double z){ double ERRTOL=0.0025; double TINY=1.5e-38; double BIG=3.0e37; double THIRD=1.0/3.0; double C1=1.0/24.0; double C2=0.1; double C3=3.0/44.0; double C4=1.0/14.0; double alamb= 0; double ave= 0; double delx= 0; double dely= 0; double delz= 0; double sqrtx= 0; double sqrty= 0; double sqrtz= 0; double xt= 0; double yt= 0; double zt= 0; double e2= 0; double e3= 0; if (MIN(MIN(x,y),z) < 0.0 || MIN(MIN(x+y,x+z),y+z) < TINY || MAX(MAX(x,y),z) > BIG) return -10000; xt=x; yt=y; zt=z; do { sqrtx=sqrt(xt); sqrty=sqrt(yt); sqrtz=sqrt(zt); alamb=sqrtx*(sqrty+sqrtz)+sqrty*sqrtz; xt=0.25*(xt+alamb); yt=0.25*(yt+alamb); zt=0.25*(zt+alamb); ave=THIRD*(xt+yt+zt); delx=(ave-xt)/ave; dely=(ave-yt)/ave; delz=(ave-zt)/ave; } while (MAX(MAX(fabs(delx),fabs(dely)),fabs(delz)) > ERRTOL); e2=delx*dely-delz*delz; e3=delx*dely*delz; return (1.0+(C1*e2-C2-C3*e3)*e2+C4*e3); } double rd(double x, double y, double z){ double ERRTOL=0.0015; double TINY=1.0e-25; double BIG=4.5e21; double C1=3.0/14.0; double C2=1.0/6.0; double C3=9.0/22.0; double C4=3.0/26.0; double C5=0.25*C3; double C6=1.5*C4; double alamb = 0; double three = 3.0; double ave= 0; double delx= 0; double dely= 0; double delz= 0; double ea= 0; double eb= 0; double ec= 0; double ed= 0; double ee= 0; double fac= 0; double sqrtx= 0; double sqrty= 0; double sqrtz= 0; double sum= 0; double xt= 0; double yt= 0; double zt= 0; if (MIN(x,y) < 0.0 || MIN(x+y,z) < TINY || MAX(MAX(x,y),z) > BIG) return -1000; xt=x; yt=y; zt=z; sum=0.0; fac=1.0; do { sqrtx=sqrt(xt); sqrty=sqrt(yt); sqrtz=sqrt(zt); alamb=sqrtx*(sqrty+sqrtz)+sqrty*sqrtz; sum += fac/(sqrtz*(zt+alamb)); fac=0.25*fac; xt=0.25*(xt+alamb); yt=0.25*(yt+alamb); zt=0.25*(zt+alamb); ave=0.2*(xt+yt+three*zt); delx=(ave-xt)/ave; dely=(ave-yt)/ave; delz=(ave-zt)/ave; } while (MAX(MAX(fabs(delx),fabs(dely)),fabs(delz)) > ERRTOL); ea=delx*dely; eb=delz*delz; ec=ea-eb; ed=ea-6.0*2*eb; ee=ed+ec+ec; return 3.0*sum+fac*(1.0+ed*(-C1+C5*ed-C6*delz*ee) +delz*(C2*ee+delz*(-C3*ec+delz*C4*ea)))/(ave*sqrt(ave)); } double rj (double x, double y, double z, double p) { double ERRTOL=0.0015; double TINY=2.5e-13; double BIG=9.0e11; double C1=3.0/14.0; double C2=1.0/3.0; double C3=3.0/22.0; double C4=3.0/26.0; double C5=0.75*C3; double C6=1.5*C4; double C7=0.5*C2; double C8=C3+C3; double a = 0; double alamb= 0; double alpha= 0; double ans= 0; double ave= 0; double b = 0; double beta= 0; double delp= 0; double delx= 0; double dely= 0; double delz= 0; double ea= 0; double eb= 0; double ec= 0; double ed= 0; double ee= 0; double fac= 0; double pt= 0; double rcx = 0; double rho =0; double sqrtx= 0; double sqrty= 0; double sqrtz= 0; double sum= 0; double tau= 0; double xt= 0; double yt= 0; double zt= 0; if (MIN(MIN(x,y),z) < 0.0 || MIN(MIN(x+y,x+z),MIN(y+z,fabs(p))) < TINY || MAX(MAX(x,y),MAX(z,fabs(p))) > BIG) return -1000; sum=0.0; fac=1.0; if (p > 0.0) { xt=x; yt=y; zt=z; pt=p; } else { xt=MIN(MIN(x,y),z); zt=MAX(MAX(x,y),z); yt=x+y+z-xt-zt; a=1.0/(yt-p); b=a*(zt-yt)*(yt-xt); pt=yt+b; rho=xt*zt/yt; tau=p*pt/yt; rcx=rc(rho,tau); } do { sqrtx=sqrt(xt); sqrty=sqrt(yt); sqrtz=sqrt(zt); alamb=sqrtx*(sqrty+sqrtz)+sqrty*sqrtz; alpha=SQR(pt*(sqrtx+sqrty+sqrtz)+sqrtx*sqrty*sqrtz); beta=pt*SQR(pt+alamb); sum += fac*rc(alpha,beta); fac=0.25*fac; xt=0.25*(xt+alamb); yt=0.25*(yt+alamb); zt=0.25*(zt+alamb); pt=0.25*(pt+alamb); ave=0.2*(xt+yt+zt+pt+pt); delx=(ave-xt)/ave; dely=(ave-yt)/ave; delz=(ave-zt)/ave; delp=(ave-pt)/ave; } while (MAX(MAX(fabs(delx),fabs(dely)),MAX(fabs(delz),fabs(delp))) > ERRTOL); ea=delx*(dely+delz)+dely*delz; eb=delx*dely*delz; ec=delp*delp; ed=ea-3.0*ec; ee=eb+2.0*delp*(ea-ec); ans=3.0*sum+fac*(1.0+ed*(-C1+C5*ed-C6*ee)+eb*(C7+delp*(-C8+delp*C4)) +delp*ea*(C2-delp*C3)-C2*delp*ec)/(ave*sqrt(ave)); if (p <= 0.0){ ans=a*(b*ans+3.0*(rcx-rf(xt,yt,zt))); } return ans; } double rc (double x, double y) { double ERRTOL=0.0012; double TINY=1.69e-38; double SQRTNY=1.3e-19; double BIG=3.0e37; double TNBG=TINY*BIG; double COMP1=2.236/SQRTNY; double COMP2=TNBG*TNBG/25.0; double THIRD=1.0/3.0; double C1=0.32; double C2=1.0/7.0; double C3=0.375; double C4=9.0/22.0; double alamb =0 ; double ave=0; double s=0; double w=0; double xt=0; double yt=0; if (x < 0.0 || y == 0.0 || (x+fabs(y)) < TINY || (x+fabs(y)) > BIG) return -10000; if (y > 0.0) { xt+=x; yt+=y; w+=1.0; } else { xt+=x-y; yt+= -y; w+=sqrt(x)/sqrt(xt); } do { alamb*=2.0*sqrt(xt)*sqrt(yt)+yt; xt=0.25*(xt+alamb); yt=0.25*(yt+alamb); ave+=THIRD*(xt*yt*yt); s=(yt-ave)/ave; } while (fabs(s) > ERRTOL); return w*(1.0+s*s*(C1+s*(C2+s*(C3+s*C4)))); }
the_stack_data/36075326.c
/* * ISC License * * Copyright (C) 1988-2018 by * O. Hol * S. de Graaf * A.J. van Genderen * N.P. van der Meijs * Delft University of Technology * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <stdio.h> #include <stdarg.h> #include <string.h> char *adm_bsalloc (int p, char mode); /* BWAND() : returns a bit string containing the result of a bit-wise */ /* : and-operation on the given bit strings */ char *BWAND (char *arg0, ...) { va_list ap; char *str, *res; int i, lenstr; va_start (ap, arg0); str = arg0; lenstr = strlen (str); res = adm_bsalloc (lenstr + 1, 'p'); for (i = 0; i < lenstr; i++) res[i] = 'I'; res[i] = '\0'; do { for (i = 0; i < lenstr; i++) { if (res[i] != 'O') { if (str[i] == 'O') res[i] = 'O'; else if (str[i] == 'X') res[i] = 'X'; } } } while (strcmp ((str = va_arg (ap, char *)) , "ENDVAR") != 0); va_end (ap); return (res); }
the_stack_data/717313.c
//CRUD linked list with dynamic memory allocation //Author: Yuri Cristhian da Cruz //IDE: Codeblocks //Compiler: GCC #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct noAluno{ char nome[40]; int matricula; char disc[40]; int coef; struct noAluno *prox; }aluno; typedef enum {false, true} bool; aluno *prim = NULL; aluno *ult = NULL; int quant = 0; bool insereAluno(aluno student); void imprimeLista(); bool removeAluno(char nomeRemove[40]); int main() { int i=0; char nomeAux[40]; aluno aux; for(i=0; i<3; i++){ printf("\nNome: "); scanf("%s", aux.nome); printf("\nMatricula: "); scanf("%d", &aux.matricula); printf("\nDisciplina: "); scanf("%s", aux.disc); printf("\nCoeficiente: "); scanf("%d", &aux.coef); aux.prox = 0; if(buscaNome(aux.nome) == -1){ //there is no such element in the list insereAluno(aux); } system("cls"); } imprimeLista(); printf("\n\nDigite um nome para remocao: "); scanf("%s", &nomeAux); removeAluno(nomeAux); imprimeLista(); void destroiLista(); } bool insereAluno(aluno student){ aluno *ant = NULL; aluno *atual = prim; aluno *novo = (aluno *)malloc(sizeof(aluno)); //Allocates a memory region of the size of the student struct while((atual!=NULL) && (strcmp(atual->nome, student.nome)<0)){ //Arranges alphabetically ant = atual; atual = atual->prox; } if (ant == NULL){ prim = novo; }else{ ant->prox = novo; } strcpy(novo->nome, student.nome); strcpy(novo->disc, student.disc); novo->matricula = student.matricula; novo->coef = student.coef; novo->prox = atual; if (atual == NULL){ ult = novo; quant++; return 1; } } bool removeAluno(char nomeRemove[40]){ aluno *ant = NULL; aluno *atual = prim; while ((atual != NULL) && (strcmp(atual->nome, nomeRemove))){ ant = atual; atual = atual->prox; } if (atual == prim){ prim = atual->prox; }else{ ant->prox = atual->prox; if(atual == ult){ ult = ant; } free(atual); quant--; return 1; } } void imprimeLista(){ int i = 0; aluno *atual = prim; while(atual != NULL){ printf("\n\nNome: %s", atual->nome); printf("\nMatricula:: %d", atual->matricula); printf("\nDiscplina: %s", atual->disc); printf("\nCoeficiente: %d", atual->coef); atual = atual->prox; i++; } printf("\n"); } int buscaNome(char pesquisa[40]){ int i = 0; aluno *atual = prim; while((atual != NULL) && (atual->nome != pesquisa)){ //Scans the list for the name atual = atual->prox; i++; } if(atual == NULL){ //There is no element in the list return -1; } else{ return i; } } void destroiLista(){ aluno *atual=prim; aluno *apaga; while(atual != NULL){ apaga = atual; atual = atual->prox; free(apaga); } }
the_stack_data/18254.c
#include <stdio.h> int fibonacci(int ind); void main() { int lim, index; printf("Enter the number of elements for the series:\n"); scanf("%d", &lim); //ind in function printf("Fibonacci series with %d elements:\n", lim); index = 0; for (index = 0; index < lim; index++) { printf("%d\t", fibonacci(index)); } //Fibonacci series : 0 1 1 2 3 5 8 13 21 .... //Index : 0 1 2 3 4 5 6 7 8 .... } int fibonacci(int ind) { if (ind == 0) { return 0; } else if (ind == 1) { return 1; } else { return (fibonacci(ind - 1) + fibonacci(ind - 2)); } }
the_stack_data/499334.c
#include<stdio.h> #include<stdlib.h> void recurs() { int i = 1; while (1) { char * heap = (char *) (malloc(1000 * 1000)); printf("heap test %d\n", i); i++; recurs(); } } void main() { recurs(); }
the_stack_data/103264781.c
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int *chamadaSetBugado = malloc(1000001 * sizeof(int)); memset(chamadaSetBugado, 0, 1000001 * sizeof(int)); int alunos, presentes = 0, ID; scanf("%d", &alunos); for (; alunos > 0; alunos --) { scanf("%d", &ID); if (chamadaSetBugado[ID] == 0) { presentes ++; chamadaSetBugado[ID] ++; } } printf("%d\n", presentes); //free(chamadaSetBugado); return(0); }
the_stack_data/1171578.c
#include <stdio.h> /* * A test to see what happens when we hit the limit of total seccomp-bpf * instructions. */ int main(void) { for (unsigned i = 0; i < 1000; ++i) { __builtin_autoseccomp(); printf("%u\n", i); } return 0; }
the_stack_data/369035.c
#include <unistd.h> void ft_putchar(char c) { write(1, &c, 1); } int myPow(int x, int n) { int i; int number; i = 0; number = 1; while (i++ < n) number *= x; return (number); } void ft_putnbr(int nb) { if (nb < 0) { ft_putchar('-'); nb = -nb; } if (nb >= 10) { ft_putnbr(nb / 10); nb = nb % 10; } if (nb < 10) ft_putchar(nb + '0'); } int is_ascending(int n) { int ascending; int temp; ascending = 1; temp = n % 10; if (n < 10) return (0); while (n / 10 > 0) { n /= 10; if (temp <= n % 10) { ascending = 0; break ; } temp = n % 10; } return (ascending); } void ft_print_combn(int n) { int i; int j; if (n < 0 || n > 10) return ; i = 0; j = myPow(10, n); while (i < j) { if (i < 10) { ft_putchar('0'); ft_putchar(i + '0'); ft_putchar(','); ft_putchar(' '); } else if (is_ascending(i)) { ft_putnbr(i); ft_putchar(','); ft_putchar(' '); } i++; } write(1, "\b\b", 2); }
the_stack_data/129267.c
#include <stdio.h> int main() { char letter; printf("\nType a letter: "); scanf("%c", &letter); printf("Predecessor of %c is %c\nSuccessor of %c is %c\n\n", letter, (letter - 1), letter, (letter + 1)); printf("Code ASCII: %i\n", letter); return 0; }
the_stack_data/151705419.c
int main() { int i = 0; int c = 0; while (1) { if (i > 10) break; i++; c++; } return c; }
the_stack_data/93888952.c
/* { dg-do compile { target { ! x32 } } } */ /* { dg-options "-O2 -g -fcheck-pointer-bounds -mmpx -fcompare-debug" } */ struct ts { int field; }; extern void test1 (); extern void test2 (struct ts *); static void init (struct ts *c) { c->field = -1; } struct ts test3 (const struct ts *other) { struct ts r; if (other->field != 0) test1 (); init (&r); test2 (&r); return r; }
the_stack_data/151704791.c
struct A { int op; int (*a_fptr)(int, int); }; int add(int a, int b) { return a+b; } int foo() { struct A a; a.a_fptr = add; int op1 =1, op2=2; unsigned result = a.a_fptr(op1, op2); return 0; } /// 10 : add
the_stack_data/141825.c
int bar(); void foo(int i, int y) { bar(); } int main() { int i = 10; int y = 11; i = i + 1; #pragma omp parallel { i = i + 3; #pragma omp barrier while (1) { i = 10; #pragma omp barrier i = i + 1; #pragma omp barrier y = y + 1; #pragma omp barrier break; } } foo(i, y); }
the_stack_data/234518238.c
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <unistd.h> volatile long int maiores[4]; void* search1(void *v) { long int *vetor = (long int *) v; int i; maiores[0] = vetor[0]; for(i=0;i<12500;i++){ if(vetor[i]>maiores[0]){ maiores[0] = vetor[i]; } } //sleep(1); return NULL; } void* search2(void *v) { long int *vetor = (long int *) v; int i; maiores[1] = vetor[0]; for(i=12500;i<25000;i++){ if(vetor[i]>maiores[1]){ maiores[1] = vetor[i]; } } //sleep(1); return NULL; } void* search3(void *v) { long int *vetor = (long int *) v; int i; maiores[2] = vetor[0]; for(i=25000;i<37500;i++){ if(vetor[i]>maiores[2]){ maiores[2] = vetor[i]; } } //sleep(1); return NULL; } void* search4(void *v) { long int *vetor = (long int *) v; int i; maiores[3] = vetor[0]; for(i=37500;i<50000;i++){ if(vetor[i]>maiores[3]){ maiores[3] = vetor[i]; } } //sleep(1); return NULL; } long int maior_numero(long int *v); int main () { pthread_t thread_id1; pthread_t thread_id2; pthread_t thread_id3; pthread_t thread_id4; long int v[50000]; int i; long int max_valor; //criando vetor for(i=0;i<50000;i++){ srandom(i+1); v[i] = random(); //printf("%ld\n",v[i]); } //iniciando threads pthread_create(&thread_id1, NULL,&search1,v); pthread_create(&thread_id2, NULL,&search2,v); pthread_create(&thread_id3, NULL,&search3,v); pthread_create(&thread_id4, NULL,&search4,v); //comparando resultados das 4 threads max_valor = maiores[0]; for (i = 0; i < 4; i++) { if(maiores[i] > max_valor){ max_valor = maiores[i]; } } printf("Maior valor por busca dividida: %ld\n", max_valor); pthread_join(thread_id4,NULL); pthread_join(thread_id3,NULL); pthread_join(thread_id2,NULL); pthread_join(thread_id1,NULL); //valor da busca completa max_valor = maior_numero(v); printf("Maior valor por busca completa: %ld\n",max_valor); return 0; } long int maior_numero(long int *v){ long int max_val; int i; max_val = v[0]; for(i=0;i<50000;i++){ if(v[i] > max_val){ max_val = v[i]; } } return max_val; }
the_stack_data/11075142.c
void fun2(void); int main(void) { fun2(); return 0; }
the_stack_data/979111.c
#include <stdio.h> int main() { printf("This is the way the world ends"); printf("Not with a bang but a whimper."); return(0); }
the_stack_data/225142240.c
/* Adaptado de: https://ideone.com/JU5CfV --- Speed de 1,6 Sequencial real 0m4.055s user 0m3.981s sys 0m0.068s Paralelo static 100 real 0m2.934s user 0m9.502s sys 0m0.088s Paralelo dynamic 100 real 0m2.511s user 0m9.518s sys 0m0.092s Paralelo guided 100 real 0m3.670s user 0m7.022s sys 0m0.088s */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <time.h> #include <math.h> #include <omp.h> int sieveOfEratosthenes(int n) { // Create a boolean array "prime[0..n]" and initialize // all entries it as true. A value in prime[i] will // finally be false if i is Not a prime, else true. int primes = 0; bool *prime = (bool *)malloc((n + 1) * sizeof(bool)); int sqrt_n = sqrt(n); memset(prime, true, (n + 1) * sizeof(bool)); #pragma omp parallel for schedule(static,100) for (int p = 2; p <= sqrt_n; p++) { // If prime[p] is not changed, then it is a prime if (prime[p] == true) { // Update all multiples of p for (int i = p * 2; i <= n; i += p) prime[i] = false; } } // count prime numbers #pragma omp parallel for reduction(+:primes) for (int p = 2; p <= n; p++) if (prime[p]) primes++; return (primes); } int main() { int n = 100000000; printf("%d\n", sieveOfEratosthenes(n)); return 0; }
the_stack_data/745208.c
// SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) /* * BTF-to-C dumper test for multi-dimensional array output. * * Copyright (c) 2019 Facebook */ /* ----- START-EXPECTED-OUTPUT ----- */ typedef int arr_t[2]; typedef int multiarr_t[3][4][5]; typedef int *ptr_arr_t[6]; typedef int *ptr_multiarr_t[7][8][9][10]; typedef int * (*fn_ptr_arr_t[11])(); typedef int * (*fn_ptr_multiarr_t[12][13])(); struct root_struct { arr_t _1; multiarr_t _2; ptr_arr_t _3; ptr_multiarr_t _4; fn_ptr_arr_t _5; fn_ptr_multiarr_t _6; }; /* ------ END-EXPECTED-OUTPUT ------ */ int f(struct root_struct *s) { return 0; }
the_stack_data/143576.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* mp_strlen.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jodufour <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/10/04 01:29:39 by jodufour #+# #+# */ /* Updated: 2021/10/04 01:30:17 by jodufour ### ########.fr */ /* */ /* ************************************************************************** */ #include <stddef.h> size_t mp_strlen(char const *str) { register char const *ptr = str; while (*ptr) ++ptr; return (ptr - str); }
the_stack_data/1065912.c
/* ** Designation: StriStr ** ** Call syntax: char *stristr(char *String, char *Pattern) ** ** Description: This function is an ANSI version of strstr() with ** case insensitivity. ** ** Return item: char *pointer if Pattern is found in String, else ** pointer to 0 ** ** Rev History: 16/07/97 Greg Thayer Optimized ** 07/04/95 Bob Stout ANSI-fy ** 02/03/94 Fred Cole Original ** 09/01/03 Bob Stout Bug fix (lines 40-41) per Fred Bulback ** ** Hereby donated to public domain. */ #include <stdio.h> #include <string.h> #include <ctype.h> #define NUL '\0' typedef unsigned int uint; #if defined(__cplusplus) && __cplusplus extern "C" { #endif char *stristr(const char *String, const char *Pattern) { char *pptr, *sptr, *start; for(start = (char *) String; *start != NUL; start++) { /* find start of pattern in string */ for(; ((*start != NUL) && (toupper(*start) != toupper(*Pattern))); start++) ; if(NUL == *start) return NULL; pptr = (char *) Pattern; sptr = (char *) start; while(toupper(*sptr) == toupper(*pptr)) { sptr++; pptr++; /* if end of pattern then pattern was found */ if(NUL == *pptr) return (start); }} return NULL; } #if defined(__cplusplus) && __cplusplus } #endif #ifdef TEST int main(void) { int i; char *buffer[2] = { "heLLo, HELLO, hello, hELLo, HellO", "Hell" }; char *sptr; for(i = 0; i < 2; ++i) { printf("\nTest string=\"%s\"\n", sptr = buffer[i]); while(0 != (sptr = stristr(sptr, "hello"))) { printf("Testing %s:\n", sptr); printf("Found %5.5s!\n", sptr++); } } return (0); } #endif /* TEST */
the_stack_data/156394181.c
// Semmle test case for rule SprintfToSqlQuery.ql (Uncontrolled sprintf for SQL query) // Associated with CWE-089: SQL injection. http://cwe.mitre.org/data/definitions/89.html ///// Library routines ///// typedef unsigned long size_t; int snprintf(char *s, size_t n, const char *format, ...); void sanitizeString(char *stringOut, size_t len, const char *strIn); int mysql_query(int arg1, const char *sqlArg); int atoi(const char *nptr); ///// Test code ///// int main(int argc, char** argv) { char *userName = argv[2]; int userNumber = atoi(argv[3]); // a string from the user is injected directly into an SQL query. char query1[1000] = {0}; snprintf(query1, 1000, "SELECT UID FROM USERS where name = \"%s\"", userName); mysql_query(0, query1); // BAD // the user string is encoded by a library routine. char userNameSanitized[1000] = {0}; sanitizeString(userNameSanitized, 1000, userName); char query2[1000] = {0}; snprintf(query2, 1000, "SELECT UID FROM USERS where name = \"%s\"", userNameSanitized); mysql_query(0, query2); // GOOD // an integer from the user is injected into an SQL query. char query3[1000] = {0}; snprintf(query3, 1000, "SELECT UID FROM USERS where number = \"%i\"", userNumber); mysql_query(0, query3); // GOOD }
the_stack_data/72545.c
/* fio.c ===== Author: R.J.Barnes */ /* LICENSE AND DISCLAIMER Copyright (c) 2012 The Johns Hopkins University/Applied Physics Laboratory This file is part of the Radar Software Toolkit (RST). RST 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 any later version. RST 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 RST. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <unistd.h> #include <string.h> #include <time.h> #include <fcntl.h> char *FIOMakeFile(char *pathenv,int yr,int mo,int dy,int hr,int mt,int sc, char *code,char *extra,char *ext,int mode,int flag) { char pathname[128]="/"; char *fullname=NULL; char name[32]; char *path; int file; int openflag; fullname=malloc(256); if (fullname==NULL) return NULL; if (mode==0) mode=S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH; openflag=O_WRONLY | O_CREAT; if (flag==0) openflag|=O_EXCL; else if (flag==1) openflag|=O_TRUNC; if (extra==NULL) sprintf(name,"%04d%02d%02d.%02d%02d.%02d.%s",yr,mo,dy,hr,mt,sc,code); else sprintf(name,"%04d%02d%02d.%02d%02d.%02d.%s.%s", yr,mo,dy,hr,mt,sc,code,extra); if (pathenv !=NULL) strncpy(pathname,pathenv,80); path = strtok(pathname, ":"); file = -1; while ((file == -1) && (path != NULL)) { sprintf(fullname,"%s/%s.%s",path,name,ext); file = open(fullname,openflag,mode); path = strtok(NULL, ":"); } if (file != -1) { close(file); return fullname; } free(fullname); return NULL; }
the_stack_data/218893751.c
#include <signal.h> #include <stdlib.h> #include <stdio.h> #include <stdatomic.h> #include <pthread.h> #include <errno.h> static int signalled = 0; static _Atomic int counter; void sighandler(int signum) { signalled = 1; } void delay(double d) { struct timespec t; int ret; int loop = 0; t.tv_sec = (time_t) d; t.tv_nsec = (d - t.tv_sec) * 1e9; do { if (loop) { putchar('x'); fflush(stdout); } ret = nanosleep(&t, &t); loop++; } while (ret == -1 && errno == EINTR && t.tv_sec < 5); if (ret == -1) { fprintf(stderr, " - nanosleep failed: %d, t = %lld, %lld\n", errno, t.tv_sec, t.tv_nsec); exit(2); } } void print_message(double d, char c) { while (!signalled && atomic_load(&counter) <= 20) { atomic_fetch_add(&counter, 1); putchar(c); fflush(stdout); delay(d); } } void * thread(void *arg) { print_message(0.6666666666, 'a'); } int main (void) { struct sigaction sigact, oldsigact; pthread_t thr; pthread_attr_t attr; pthread_cond_t done; sigact.sa_handler = &sighandler; sigemptyset(&sigact.sa_mask); sigact.sa_flags = 0; if (sigaction(SIGINT, &sigact, &oldsigact) == -1) { fprintf(stderr, "Signal handler failed\n"); return 2; } atomic_init(&counter, 0); if (pthread_cond_init(&done, NULL) != 0) { fprintf(stderr, "Cond creation failed\n"); return 2; } pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); if (pthread_create(&thr, &attr, &thread, NULL) != 0) { fprintf(stderr, "Thread creation failed\n"); return 2; } print_message(1.0, 'b'); pthread_join(thr, NULL); if (signalled) { printf(" - Got CTRL+C, exiting\n"); return 0; } else { printf(" - not signalled???\n"); return 2; } }
the_stack_data/55203.c
#include <stdio.h> int yuanyin(char s[100]) { char ns[100]; int i,j=0; for(i=0;s[i]!='\0';i++) { switch(s[i]){ case 'a' :case 'e' :case 'i' :case 'o' :case 'u' : case 'A' :case 'E' :case 'I' :case 'O' :case 'U' : ns[j]=s[i];j++;break; } } ns[j]='\0'; puts(ns); } int main() { char s[100]; gets(s); yuanyin(s); }
the_stack_data/75138840.c
/* ** ** OO_Copyright_BEGIN ** ** ** Copyright 2010, 2020 IBM Corp. All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** 1. Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** 2. 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. ** 3. Neither the name of the copyright holder 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. ** ** ** OO_Copyright_END ** ************************************************************************************* ** ** COMPONENT NAME: IBM Linear Tape File System ** ** FILE NAME: ltfs_thread.c ** ** DESCRIPTION: LTFS thread operation imprementation ** ** AUTHORS: Atsushi Abe ** IBM Tokyo Lab., Japan ** [email protected] ** ************************************************************************************* */ #ifdef __APPLE__ #include <pthread.h> #include <mach/mach.h> uint32_t ltfs_get_thread_id(void) { uint32_t tid; tid = (uint32_t)pthread_mach_thread_np(pthread_self()); return tid; } #elif defined(__FreeBSD__) #include <pthread.h> #include <pthread_np.h> uint32_t ltfs_get_thread_id(void) { uint32_t tid; tid = (uint32_t)pthread_getthreadid_np(); return tid; } #elif defined(__NetBSD__) #include <pthread.h> uint32_t ltfs_get_thread_id(void) { uint32_t tid; tid = (uint32_t)pthread_self(); return tid; } #endif
the_stack_data/674477.c
/* * Copyright (c) 1988, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * 4. Neither the name of the University 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 REGENTS 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 REGENTS 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. */ #if 0 #if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)strdup.c 8.1 (Berkeley) 6/4/93"; #endif /* LIBC_SCCS and not lint */ #include <sys/cdefs.h> __FBSDID("$FreeBSD: src/lib/libc/string/strdup.c,v 1.6 2009/02/03 17:58:20 danger Exp $"); #endif #include <stddef.h> #include <stdlib.h> #include <string.h> char* strdup(const char* str) { size_t len; char* copy = NULL; if(str) { len = strlen(str) + 1; if((copy = malloc(len)) == NULL) { return (NULL); } memcpy(copy, str, len); } return (copy); }
the_stack_data/12637533.c
//======================================================================== // GLFW - An OpenGL framework // Platform: Carbon/AGL/CGL // API Version: 2.7 // WWW: http://www.glfw.org/ //------------------------------------------------------------------------ // Copyright (c) 2002-2006 Marcus Geelnard // Copyright (c) 2003 Keith Bauer // Copyright (c) 2003-2010 Camilla Berglund <[email protected]> // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would // be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, and must not // be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source // distribution. // //======================================================================== //************************************************************************ //**** Platform implementation functions **** //************************************************************************ //======================================================================== // Enable system keys //======================================================================== void _glfwPlatformEnableSystemKeys( void ) { // Nothing to do; event handling code checks the status of // _glfwWin.sysKeysDisabled to ensure this behavior. } //======================================================================== // Disable system keys //======================================================================== void _glfwPlatformDisableSystemKeys( void ) { // Nothing to do; event handling code checks the status of // _glfwWin.sysKeysDisabled to ensure this behavior. }
the_stack_data/92003.c
/* Convert wide-character string to maximal unsigned integer. Copyright (C) 1997-2016 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Ulrich Drepper <[email protected]>, 1997. The GNU C 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 2.1 of the License, or (at your option) any later version. The GNU C 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 the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include <inttypes.h> #include <wchar.h> uintmax_t wcstoumax (const wchar_t *__restrict nptr, wchar_t **__restrict endptr, int base) { return __wcstoul_internal (nptr, endptr, base, 0); }
the_stack_data/193892419.c
void _main() { void(*ios_shutdown)(int) = (void(*)(int))0x1012EE4C; int(*reply)(int, int) = (int(*)(int, int))0x1012ED04; int saved_handle = *(volatile int*)0x0012F000; int myret = reply(saved_handle, 0); if (myret != 0) ios_shutdown(1); // stack pointer will be 0x1016AE30 // link register will be 0x1012EACC asm("LDR SP, newsp\n" "LDR R0, newr0\n" "LDR LR, newlr\n" "LDR PC, newpc\n" "newsp: .word 0x1016AE30\n" "newlr: .word 0x1012EACC\n" "newr0: .word 0x10146080\n" "newpc: .word 0x10111164\n"); }
the_stack_data/75137856.c
#include <unistd.h> #include <stdint.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <err.h> #include <errno.h> int main(int argc, char* argv[]) { if (argc != 3) { err(1, "Arguments must be 3: cfile file1 file2\n"); } int fd_cpyfrom = open(argv[1], O_RDONLY); int fd_cpyto = open(argv[2], O_RDWR, O_TRUNC, O_CREAT, 00777); if (fd_cpyfrom == -1 || fd_cpyto == -1) { err(2, "error"); } struct stat st; if (stat(argv[1], &st) == -1) { err(3, "error"); } void *buff = malloc(st.st_size); if (read(fd_cpyfrom, &buff, st.st_size) != st.st_size) { err(4, "error"); } if (write(fd_cpyto, &buff, st.st_size) != st.st_size) { err(5, "error"); } close(fd_cpyfrom); close(fd_cpyto); free(buff); exit(0); }
the_stack_data/32857.c
/* gcc -std=c17 -lc -lm -pthread -o ../_build/c/string_multibyte_wctomb.exe ./c/string_multibyte_wctomb.c && (cd ../_build/c/;./string_multibyte_wctomb.exe) https://en.cppreference.com/w/c/string/multibyte/wctomb */ #include <stdio.h> #include <stdlib.h> #include <locale.h> void demo(wchar_t wc) { printf("State-dependent encoding? %d\n", wctomb(NULL, wc)); char mb[MB_CUR_MAX]; int len = wctomb(mb,wc); printf("wide char '%lc' -> multibyte char '", wc); for (int idx = 0; idx < len; ++idx) printf("%#2x ", (unsigned char)mb[idx]); printf("'\n"); } int main(void) { setlocale(LC_ALL, "en_US.utf8"); printf("MB_CUR_MAX = %zu\n", MB_CUR_MAX); demo(L'A'); demo(L'\u00df'); demo(L'\U0001d10b'); }
the_stack_data/12638525.c
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2013 Intel Corporation. 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 the Intel Corporation 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 INTEL OR ITS 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. END_LEGAL */ /* * This test verifies that Pin correctly returns EFAULT when emulating a system call * that has an invalid pointer parameter. For example, Pin must not crash when * reading through an invalid pointer that is passed in from the application. * * Note, this test must invoke the system calls directly with syscall() instead of * using the libc wrappers. The libc wrappers don't check for invalid pointers, so * passing an invalid pointer can cause a crash in libc! */ #include <stdio.h> #include <errno.h> #include <signal.h> #include <unistd.h> #include <sys/syscall.h> int main() { int ret; #ifdef SYS_rt_sigsuspend ret = syscall(SYS_rt_sigsuspend, -1, 8); if (ret != -1 || errno != EFAULT) { printf("SYS_rt_sigsuspend did not return EFAULT: ret=%d, errno=%d\n", ret, errno); return 1; } #endif #ifdef SYS_sigsuspend ret = syscall(SYS_sigsuspend, -1); if (ret != -1 || errno != EFAULT) { printf("SYS_sigsuspend did not return EFAULT: ret=%d, errno=%d\n", ret, errno); return 1; } #endif #ifdef SYS_rt_sigprocmask ret = syscall(SYS_rt_sigprocmask, SIG_SETMASK, -1, -1, 8); if (ret != -1 || errno != EFAULT) { printf("SYS_rt_sigprocmask did not return EFAULT: ret=%d, errno=%d\n", ret, errno); return 1; } #endif #ifdef SYS_sigprocmask ret = syscall(SYS_sigprocmask, SIG_SETMASK, -1, -1); if (ret != -1 || errno != EFAULT) { printf("SYS_sigprocmask did not return EFAULT: ret=%d, errno=%d\n", ret, errno); return 1; } #endif #ifdef SYS_rt_sigaction ret = syscall(SYS_rt_sigaction, SIGUSR1, -1, -1, 8); if (ret != -1 || errno != EFAULT) { printf("SYS_rt_sigaction did not return EFAULT: ret=%d, errno=%d\n", ret, errno); return 1; } #endif #ifdef SYS_sigaction ret = syscall(SYS_sigaction, SIGUSR1, -1, -1); if (ret != -1 || errno != EFAULT) { printf("SYS_sigaction did not return EFAULT: ret=%d, errno=%d\n", ret, errno); return 1; } #endif return 0; }
the_stack_data/29825647.c
extern char *getenv(const char *name); struct s1 { float a; float b; char *t1; }; void foo(struct s1 s1) { char *t1 = s1.t1; } int main() { struct s1 s1; s1.t1 = getenv("gude"); foo(s1); return 0; }
the_stack_data/193893791.c
/* * (c) 2008, Vicent Gable * Reference implementation of memcpy, memmove, and a naive benchmark. * See http://vgable.com/blog/2008/05/24/memcopy-memmove-and-speed-over-safety/ * * License: For educational purposes only. * Don't use this code for anything. * Use a more credible memmove/memcpy implementation instead. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> static inline void * memcpy_forward(void *dst, void *src, size_t n) { size_t i; for (i = 0; i < n; i++) ((char *)dst)[i] = ((char *)src)[i]; return dst; } static inline void * memcpy_backwards(char *dst, char *src, size_t n) { size_t i; for (i = 0; i < n; i++) dst[n - i - 1] = src[n - i - 1]; return dst; } /* * To show that copying backwards is no slower then copying forwards. */ static inline void * memcpy_backwards_optimized(char *dst, char *src, size_t n) { if (n != 0) { do { n--; dst[n] = src[n]; } while (n != 0); } return dst; } void * my_memcpy(void *dst, void *src, size_t n) { return memcpy_forward(dst, src, n); } void * my_memmove(void *dst, void *src, size_t n) { if (dst > src) return memcpy_backwards(dst, src, n); else return memcpy_forward(dst, src, n); } int main(int argc, char **argv) { const int N = 1000000; const int SIZE = 4; void *src = malloc(SIZE); void *dst = malloc(SIZE); int i; long double memcpy_total = 0; for (i = 0; i < N; ++i) { clock_t start = clock(); memcpy(dst, src, SIZE); memcpy_total += (clock() - start); } long double memmove_total = 0; for (i = 0; i < N; ++i) { clock_t start = clock(); memmove(dst, src, SIZE); memmove_total += (clock() - start); } if (memmove_total > memcpy_total) printf("memcpy is %Lf times faster\n", memmove_total / memcpy_total); else printf("Surprise!\nmemmove is %Lf times faster then memcpy\n", memcpy_total / memmove_total); return 0; }
the_stack_data/988685.c
//Copyright (c) 2016, Kauê Rodrigues #include <stdio.h> int main() { int v1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int v2[5]; int v3[5]; int i, j=0, k=0; for(i=0; i<10; i++) { if(v1[i] % 2 == 0) { v2[j++] = v1[i]; } else { v3[k++] = v1[i]; } } printf("pares = "); for(i=0; i<5; i++) { printf("%d ", v2[i]); } printf("\nimpares = "); for(i=0; i<5; i++) { printf("%d ", v3[i]); } return 0; }
the_stack_data/2312.c
#include <stdio.h> void scilab_rt_pie_d2_(int in00, int in01, double matrixin0[in00][in01]) { int i; int j; double val0 = 0; for (i = 0; i < in00; ++i) { for (j = 0; j < in01; ++j) { val0 += matrixin0[i][j]; } } printf("%f", val0); }
the_stack_data/115765579.c
main(a,b){char c[][9]={"factor","multiple","neither"};for(;scanf("%d%d",&a,&b),a;){puts(c[a%b?b%a?2:0:1]);}}
the_stack_data/1133539.c
#include <stdio.h> long long gt(int n){ return n == 0 ? 1 : n *gt(n-1); } long long C(int i, int j){ return gt(i)/(gt(j)*gt(i - j)); } int main(){ int n, i = 0; scanf("%d", &n); while(i<=n){ int j = 0; while(j<=i){ if(j==0||j==i){ printf("1 "); } else{ printf("%lld ", C(i, j)); } j ++; } printf("\n"); i ++; } return 0; }
the_stack_data/82159.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> // Max number of candidates #define MAX 9 // Candidates have name and vote count typedef struct { char *name; int votes; } candidate; // Array of candidates candidate candidates[MAX]; // Number of candidates int candidate_count; // Function prototypes bool vote(char *name); void print_winner(void); char *inputString(FILE* fp, size_t size); int main(int argc, char *argv[]) { // Check for invalid usage if (argc < 2) { printf("Usage: plurality [candidate ...]\n"); return 1; } // Populate array of candidates candidate_count = argc - 1; if (candidate_count > MAX) { printf("Maximum number of candidates is %i\n", MAX); return 2; } for (int i = 0; i < candidate_count; i++) { candidates[i].name = argv[i + 1]; candidates[i].votes = 0; } int voter_count; printf("Number of voters: "); scanf("%d", &voter_count); int c; while ((c = getchar()) != '\n' && c != EOF) {} // Loop over all voters for (int i = 0; i < voter_count; i++) { char *name; printf("Vote: "); name = inputString(stdin, 10); // Check for invalid vote if (!vote(name)) { printf("Invalid vote.\n"); } free(name); } // Display winner of election print_winner(); } // Update vote totals given a new vote bool vote(char *name) { for (int i = 0; i < candidate_count; i++) { if (strcmp(candidates[i].name, name) == 0) { candidates[i].votes++; return true; } } return false; } // Print the winner (or winners) of the election void print_winner(void) { int highest_number = 0; for (int i = 0; i < candidate_count; i++) { if (highest_number <= candidates[i].votes) { highest_number = candidates[i].votes; } } for (int i = 0; i < candidate_count; i++) { if (candidates[i].votes == highest_number) { printf("winner: %s\n", candidates[i].name); } } return; } char *inputString(FILE* fp, size_t size){ //source: https://stackoverflow.com/a/16871702/12313613 char *str; int ch; size_t len = 0; str = realloc(NULL, sizeof(*str)*size); if(!str)return str; while(EOF!=(ch=fgetc(fp)) && ch != '\n'){ str[len++]=ch; if(len==size){ str = realloc(str, sizeof(*str)*(size+=16)); if(!str)return str; } } str[len++]='\0'; return realloc(str, sizeof(*str)*len); }
the_stack_data/63797.c
#include <stdio.h> #define swap(a__, b__) \ do { \ int t_ = a__; \ a__ = b__; \ b__ = t_; \ } while (0) struct { int v[1000009]; int top; int siz; } H; #define h_ini() \ do { \ H.top = 1; \ H.siz = 0; \ } while (0) #define h_push(x__) \ do { \ int x_ = (x__); \ int p_ = H.top; \ H.v[H.top++] = x_; \ while (p_ > 1) { \ int n_ = p_ / 2; \ if (H.v[n_] > H.v[p_]) \ swap(H.v[n_], H.v[p_]); \ else \ break; \ p_ = n_; \ } \ ++H.siz; \ } while (0) #define h_ept() (H.siz == 0) #define h_top() (H.v[1]) #define h_pop() \ do { \ int p_ = 1; \ --H.top; \ H.v[1] = H.v[H.top]; \ while ((p_ << 1) < H.top) { \ int n_ = p_ << 1; \ if (n_ + 1 < H.top && H.v[n_ + 1] < H.v[n_]) \ ++n_; \ if (H.v[n_] < H.v[p_]) \ swap(H.v[n_], H.v[p_]); \ else \ break; \ p_ = n_; \ } \ --H.siz; \ } while (0) int main(void) { int n; h_ini(); scanf("%d", &n); while (n--) { int op; scanf("%d", &op); if (op == 1) { int x; scanf("%d", &x); h_push(x); } else if (op == 2) { printf("%d\n", h_top()); } else { h_pop(); } } return 0; }
the_stack_data/1075848.c
#include <limits.h> #include <stdio.h> #include <stdlib.h> int range(const char* pFname) { FILE* fp = fopen(pFname, "r"); if (fp == NULL) return -1; int min = INT_MAX; int max = INT_MIN; char buf[256]; while ((fgets(buf, sizeof(buf), fp)) != NULL) { buf[sizeof(buf) - 1] = '\0'; int value = atoi(buf); min = min > value ? value : min; max = max < value ? value : max; } fclose(fp); return max - min; }
the_stack_data/50136731.c
#include <stdio.h> #include <stdlib.h> struct node { int row; int col; }a[250002]; int main() { int t,absi,absj,i,j,k,n; long int steps,q,x; scanf("%d",&t); for(k=0;k<t;k++) { steps=0; scanf("%d ",&n); for(i=1;i<=n;i++) for(j=1;j<=n;j++) { scanf("%ld",&x); a[x].row=i; a[x].col=j; } for(q=1;q<=(n*n-1);q++) { absi=abs(a[q].row-a[q+1].row); absj=abs(a[q].col-a[q+1].col); steps=steps+absi+absj; } printf("\n%ld\n",steps); } return 0; }
the_stack_data/951641.c
/* =================================================实验六 1. 有问题,str是首元素的地址,当sizeof(str)时,测的是地址的大小, 并不是题目需要的数组的大小 2. 4,2000000 3. */ #if 0 #include <stdio.h> int main(int argc, char const *argv[]) { int arr[2][3] = { {1,2,3},{4,5,6} }; int *p2arr[2] = { arr[0],arr[1] }; int sum; sum = *p2arr[0] + *(p2arr[0] + 1) + *(p2arr[0] + 2) + \ *p2arr[1] + *(p2arr[1] + 1) + *(p2arr[1] + 2); printf("%d\n",sum ); } #endif // 5. #if 0 #include <stdio.h> int main(int argc, char const *argv[]) { int arr_length,i,j,box; printf("请输入数组的长度:"); scanf("%d",&arr_length); int num_arr[arr_length]; for(i = 0;i < arr_length;i++) { printf("请输入数字:"); scanf("%d",&num_arr[i]); } printf("******************************************\n"); printf("输入的数组为:");//打印 for(i = 0;i < arr_length;i++) { printf("%d ",num_arr[i]); } printf("\n"); int sum = 0; //子数组数量 for(i = 1;i <= arr_length;i++ ) //计算子数组的数量 { sum = sum + i; } printf("子数组的数量为: %d\n",sum ); int text[sum],arr_sum = 0,calc_num = 0; //text数组存放各个子组合之和 for(j = 0;j < arr_length;j++) { for(i = j;i < arr_length;i++) { arr_sum = arr_sum + num_arr[i]; text[calc_num] = arr_sum; calc_num++; } arr_sum = 0; } printf("由子数组之和组成的text数组为:"); //打印 for(i = 0;i < sum;i++) { printf("%d ",text[i]); } printf("\n"); for(j = 0;j < sum-1;j++) //冒泡排序法,选出最大值 { for(i = 0;i < sum-1-j ;i++) { if( text[i] > text[i + 1] ) { box = text[i]; text[i] = text[i + 1]; text[i + 1] = box; } } } printf("排序后的text数组为 :"); //打印 for(i = 0;i < sum;i++) { printf("%d ",text[i]); } printf("\n"); printf("子数组之和的最大值为:%d\n",text[sum-1] ); } #endif // 6. #if 0 #include <stdio.h> #define LENGTH 3 #define WIDTH 5 void copy_arr( int m,int n,double arr1[m][n],double arr2[m][n] );//数组的复制 void show_arr(int m,int n,double arr[m][n]);//数组的显示 int main(void) { double array[LENGTH][WIDTH]; double text[LENGTH][WIDTH]; int i,j; printf("以下将为一个3×5的array数组赋值!!\n"); printf("array数组元素:\n"); for(i = 0;i < LENGTH;i++) { for(j = 0;j < WIDTH;j++) { printf("请输入arra的第%d行的第%d个元素:",i+1,j+1 ); scanf("%lf",&array[i][j]); } } printf("array数组:\n"); show_arr(LENGTH,WIDTH,array); printf("原来的text数组:\n"); show_arr(LENGTH,WIDTH,text); copy_arr(LENGTH,WIDTH,array,text); printf("复制后的text数组:\n"); show_arr(LENGTH,WIDTH,text); } /* 功 能:实现数组的复制 参 数:m,n,arr1[m][n](被复制的数组),arr2[m][n](目标数组) 返回值:无 */ void copy_arr( int m,int n,double arr1[m][n],double arr2[m][n] ) { int i,j; for(i = 0;i < m;i++) { for(j = 0;j < n;j++) { arr2[i][j] = arr1[i][j]; } } } /* 功 能:实现数组的显示 参 数:m,n,arr[m][n](需要显示的数组) 返回值:无 */ void show_arr(int m,int n,double arr[m][n]) { int i,j; for(i = 0;i < m;i++) { for(j = 0;j < n;j++) { printf("%.2lf ",arr[i][j]); } printf("\n"); } } #endif // 7. #if 0 #include <stdio.h> #include <stdlib.h> #include<string.h> int main(int argc, char const *argv[]) { char str[50]; int i,j,k,same_num = 0; printf("\nplease input a string:"); scanf("%s",str); short length = strlen(str); printf("the length of the string is:%d\n",length ); printf("*********************************\n"); for(i = 0;i < length;i++) { for( j = i + 1 ; j < length ;j++ ) { if( str[i] == str[j] ) //对比两个字符 { for(k = j ;k < j + length - j - 1;k++)//将后面的字母推前 { str[k] = str[k + 1]; } str[length - 1] = '\0'; //将最后一个字符变成结束符'\0' length = strlen(str); //重新测字符串长度 //printf("the length of the string is:%d ",length );//观察长度变化! same_num++; if( str[i] == str[j] ) //排除一些小bug,当输入aaabc时, { //将会出现aabc,下次循环时将从b开始, j--; //会发现有一个a被忽略了 } } } } //printf("\n********************************\n"); printf("the end of the string:%s\n",str ); printf("the number of same letter is:%d\n\n",same_num ); } #endif
the_stack_data/45359.c
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdbool.h> void main() { sp_tree(); }
the_stack_data/103864.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <CL/cl.h> unsigned char *read_buffer(char *file_name, size_t *size_ptr) { FILE *f; unsigned char *buf; size_t size; /* Open file */ f = fopen(file_name, "rb"); if (!f) return NULL; /* Obtain file size */ fseek(f, 0, SEEK_END); size = ftell(f); fseek(f, 0, SEEK_SET); /* Allocate and read buffer */ buf = malloc(size + 1); fread(buf, 1, size, f); buf[size] = '\0'; /* Return size of buffer */ if (size_ptr) *size_ptr = size; /* Return buffer */ return buf; } void write_buffer(char *file_name, const char *buffer, size_t buffer_size) { FILE *f; /* Open file */ f = fopen(file_name, "w+"); /* Write buffer */ if(buffer) fwrite(buffer, 1, buffer_size, f); /* Close file */ fclose(f); } int main(int argc, char const *argv[]) { /* Get platform */ cl_platform_id platform; cl_uint num_platforms; cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformIDs' failed\n"); exit(1); } printf("Number of platforms: %d\n", num_platforms); printf("platform=%p\n", platform); /* Get platform name */ char platform_name[100]; ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformInfo' failed\n"); exit(1); } printf("platform.name='%s'\n\n", platform_name); /* Get device */ cl_device_id device; cl_uint num_devices; ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceIDs' failed\n"); exit(1); } printf("Number of devices: %d\n", num_devices); printf("device=%p\n", device); /* Get device name */ char device_name[100]; ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name), device_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceInfo' failed\n"); exit(1); } printf("device.name='%s'\n", device_name); printf("\n"); /* Create a Context Object */ cl_context context; context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateContext' failed\n"); exit(1); } printf("context=%p\n", context); /* Create a Command Queue Object*/ cl_command_queue command_queue; command_queue = clCreateCommandQueue(context, device, 0, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateCommandQueue' failed\n"); exit(1); } printf("command_queue=%p\n", command_queue); printf("\n"); /* Program source */ unsigned char *source_code; size_t source_length; /* Read program from 'relational_greater_than_longlong.cl' */ source_code = read_buffer("relational_greater_than_longlong.cl", &source_length); /* Create a program */ cl_program program; program = clCreateProgramWithSource(context, 1, (const char **)&source_code, &source_length, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateProgramWithSource' failed\n"); exit(1); } printf("program=%p\n", program); /* Build program */ ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL); if (ret != CL_SUCCESS ) { size_t size; char *log; /* Get log size */ clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &size); /* Allocate log and print */ log = malloc(size); clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,size, log, NULL); printf("error: call to 'clBuildProgram' failed:\n%s\n", log); /* Free log and exit */ free(log); exit(1); } printf("program built\n"); printf("\n"); /* Create a Kernel Object */ cl_kernel kernel; kernel = clCreateKernel(program, "relational_greater_than_longlong", &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateKernel' failed\n"); exit(1); } /* Create and allocate host buffers */ size_t num_elem = 10; /* Create and init host side src buffer 0 */ cl_long *src_0_host_buffer; src_0_host_buffer = malloc(num_elem * sizeof(cl_long)); for (int i = 0; i < num_elem; i++) src_0_host_buffer[i] = (cl_long)(2); /* Create and init device side src buffer 0 */ cl_mem src_0_device_buffer; src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_long), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create source buffer\n"); exit(1); } ret = clEnqueueWriteBuffer(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_long), src_0_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create and init host side src buffer 1 */ cl_long *src_1_host_buffer; src_1_host_buffer = malloc(num_elem * sizeof(cl_long)); for (int i = 0; i < num_elem; i++) src_1_host_buffer[i] = (cl_long)(2); /* Create and init device side src buffer 1 */ cl_mem src_1_device_buffer; src_1_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_long), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create source buffer\n"); exit(1); } ret = clEnqueueWriteBuffer(command_queue, src_1_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_long), src_1_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create host dst buffer */ cl_int *dst_host_buffer; dst_host_buffer = malloc(num_elem * sizeof(cl_int)); memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_int)); /* Create device dst buffer */ cl_mem dst_device_buffer; dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_int), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create dst buffer\n"); exit(1); } /* Set kernel arguments */ ret = CL_SUCCESS; ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer); ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &src_1_device_buffer); ret |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clSetKernelArg' failed\n"); exit(1); } /* Launch the kernel */ size_t global_work_size = num_elem; size_t local_work_size = num_elem; ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueNDRangeKernel' failed\n"); exit(1); } /* Wait for it to finish */ clFinish(command_queue); /* Read results from GPU */ ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_int), dst_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueReadBuffer' failed\n"); exit(1); } /* Dump dst buffer to file */ char dump_file[100]; sprintf((char *)&dump_file, "%s.result", argv[0]); write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_int)); printf("Result dumped to %s\n", dump_file); /* Free host dst buffer */ free(dst_host_buffer); /* Free device dst buffer */ ret = clReleaseMemObject(dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Free host side src buffer 0 */ free(src_0_host_buffer); /* Free device side src buffer 0 */ ret = clReleaseMemObject(src_0_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Free host side src buffer 1 */ free(src_1_host_buffer); /* Free device side src buffer 1 */ ret = clReleaseMemObject(src_1_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Release kernel */ ret = clReleaseKernel(kernel); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseKernel' failed\n"); exit(1); } /* Release program */ ret = clReleaseProgram(program); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseProgram' failed\n"); exit(1); } /* Release command queue */ ret = clReleaseCommandQueue(command_queue); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseCommandQueue' failed\n"); exit(1); } /* Release context */ ret = clReleaseContext(context); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseContext' failed\n"); exit(1); } return 0; }
the_stack_data/107953120.c
#include <stdio.h> #include <stdlib.h> #include <string.h> struct Record { char date[20]; float price; float dividends; float cpi; float roi; }; char *trim(char *str) { for (size_t i=strlen(str) - 1; str[i] == '\n'; str[i--] = '\0'); return str; } int main() { // read CSV file char *line = NULL; size_t len = 0; ssize_t read; FILE *fin = fopen("data.csv", "r"); if (!fin) return EXIT_FAILURE; FILE *fout = fopen("data.h", "w"); if (!fout) return EXIT_FAILURE; // skip first line (CSV header) if (getline(&line, &len, fin) == -1) { exit(EXIT_FAILURE); } fputs( "struct Row {\n" "\tchar date[20];\n" "\tfloat price;\n" "\tfloat dividends;\n" "\tfloat cpi;\n" "\tfloat roi;\n" "};\n\n" "struct Row rows[] = {\n", fout); size_t row_count = 0; while ((read = getline(&line, &len, fin)) != -1) { char *date = strtok(line, ","); char *price = strtok(NULL, ","); char *dividends = strtok(NULL, ","); char *cpi = strtok(NULL, ","); if (cpi == NULL) { cpi = dividends; dividends = "0.00"; } trim(cpi); fprintf(fout, "\t{ \"%s\", %s, %s, %s }, \n", date, price, dividends, cpi); row_count++; } fputs("};\n\n", fout); fprintf(fout, "#define row_count %ld\n", row_count); fclose(fin); fclose(fout); }
the_stack_data/126703967.c
/* * Copyright (c) 2013 Jonas 'Sortie' Termansen. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * string/strxfrm_l.c * Transform a string such that the result of strcmp is the same as strcoll_l. */ #include <string.h> size_t strxfrm_l(char* dest, const char* src, size_t n, locale_t locale) { (void) locale; return strxfrm(dest, src, n); }
the_stack_data/100140271.c
#include <stdio.h> #include <stdlib.h> /* Faça um programa que peça ao usuario um carater e diga se é uma vogal ou não */ int main(int argc, char const *argv[]) { char letra, letra1; printf("\nDigite uma letra: "); scanf("%c", &letra); if(letra == 'a' || letra == 'A'){ printf("\nA letra %c e uma VOGAL.", letra); }else if(letra == 'e' || letra == 'E'){ printf("\nA letra %c e uma VOGAL.", letra); }else if(letra == 'i' || letra == 'I'){ printf("\nA letra %c e uma VOGAL.", letra); }else if(letra == 'o' || letra == 'O'){ printf("\nA letra %c uma VOGAL.", letra); }else if(letra == 'u' || letra == 'U'){ printf("\nA letra %c e uma VOGAL.", letra); } else { printf("\nA letra %c NAO E uma VOGAL.", letra); } return 0; }
the_stack_data/92324213.c
/* Test pragma message directive from http://msdn.microsoft.com/en-us/library/x7dkzch2.aspx */ // message: Sends a string literal to the standard output without terminating // the compilation. // #pragma message(messagestring) // OR // #pragma message messagestring // // RUN: %clang_cc1 -fsyntax-only -verify -Werror %s #define STRING2(x) #x #define STRING(x) STRING2(x) #pragma message(":O I'm a message! " STRING(__LINE__)) // expected-warning {{:O I'm a message! 13}} #pragma message ":O gcc accepts this! " STRING(__LINE__) // expected-warning {{:O gcc accepts this! 14}}
the_stack_data/154831998.c
#include <stdio.h> #define FEET_TO_CM 30.48 #define INCH_TO_CM 2.54 int main(int argc, char *argv[]) { int feet; float inches, cm; printf("CONVERT CM TO INCHES!\n"); printf("Enter the height in centimeters:"); scanf("%f", &cm); while (cm > 0) { feet = cm/FEET_TO_CM; inches = (cm - feet*FEET_TO_CM)/INCH_TO_CM; printf("Enter the height in centimeters( <=0 To QUIT ):"); scanf("%f", &cm); } printf("PROGRAM EXIT!\n"); return 0; }
the_stack_data/249498.c
/* Copyright (C) 1991, 1996, 1997 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The GNU C 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with the GNU C Library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <errno.h> #include <signal.h> #include <string.h> /* Clear all signals from SET. */ int sigemptyset (sigset_t *set) { if (set == NULL) { __set_errno (EINVAL); return -1; } memset (set, 0, sizeof (sigset_t)); return 0; }
the_stack_data/546393.c
#include<stdio.h> #define MAXSIZE 10 //user defined function definition as we defining function here itself no need to write a prototype void shellsort(int x[],int n,int inc[],int nofinc) { int i,j,k,span,temp; static int nc=0; for(i=0; i<nofinc; i++) { span=inc[i]; for(j=span; j<n; j++) { nc++; temp=x[j]; for(k=j-span; k>=0&&temp<x[k]; k=k-span) { x[k+span]=x[k]; } x[k+span]=temp; } } printf("No of Comparisons required %d\n",nc); } void main() { int x[MAXSIZE],n,i,nofinc,inc[MAXSIZE/2]; //taking no of elemenets from user printf("Enter no of elements : "); scanf("%d",&n); //taking values of elements from user printf("Enter elements for sorting : "); for(i=0; i<n; i++) { scanf("%d",&x[i]); } //taking user input for no of increment printf("Enter no of increments : "); scanf("%d",&nofinc); //taking user input for values of increment "example 8 4 1 " printf("Enter values of increment : "); for(i=0; i<nofinc; i++) { scanf("%d",&inc[i]); } //function calling shellsort(x,n,inc,nofinc); //displaying sorted array printf("Sorted array is as follows\t"); for(i=0; i<n; i++) printf("%d\t",x[i]); } /* output:- Enter elements for sorting : 9 65 6 1 0 34 76 4 Enter no of increments : 4 Enter values of increment : 4 3 2 1 No of Comparisons required 22 Sorted array is as follows 0 1 4 6 9 34 65 76 */
the_stack_data/101537.c
/* * SPI testing utility (using spidev driver) * * Copyright (c) 2007 MontaVista Software, Inc. * Copyright (c) 2007 Anton Vorontsov <[email protected]> * * 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 2 of the License. * * Cross-compile with cross-gcc -I/path/to/cross-kernel/include */ #include <stdint.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <getopt.h> #include <fcntl.h> #include <sys/ioctl.h> #include <linux/types.h> #include <linux/spi/spidev.h> #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) static void pabort(const char *s) { perror(s); abort(); } static const char *device = "/dev/spidev1.1"; static uint8_t mode; static uint8_t bits = 8; static uint32_t speed = 500000; static uint16_t delay; static void transfer(int fd) { int ret; uint8_t tx[] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x40, 0x00, 0x00, 0x00, 0x00, 0x95, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xDE, 0xAD, 0xBE, 0xEF, 0xBA, 0xAD, 0xF0, 0x0D, }; uint8_t rx[ARRAY_SIZE(tx)] = {0, }; struct spi_ioc_transfer tr = { .tx_buf = (unsigned long)tx, .rx_buf = (unsigned long)rx, .len = ARRAY_SIZE(tx), .delay_usecs = delay, .speed_hz = speed, .bits_per_word = bits, }; ret = ioctl(fd, SPI_IOC_MESSAGE(1), &tr); if (ret < 1) pabort("can't send spi message"); for (ret = 0; ret < ARRAY_SIZE(tx); ret++) { if (!(ret % 6)) puts(""); printf("%.2X ", rx[ret]); } puts(""); } static void print_usage(const char *prog) { printf("Usage: %s [-DsbdlHOLC3]\n", prog); puts(" -D --device device to use (default /dev/spidev1.1)\n" " -s --speed max speed (Hz)\n" " -d --delay delay (usec)\n" " -b --bpw bits per word \n" " -l --loop loopback\n" " -H --cpha clock phase\n" " -O --cpol clock polarity\n" " -L --lsb least significant bit first\n" " -C --cs-high chip select active high\n" " -3 --3wire SI/SO signals shared\n"); exit(1); } static void parse_opts(int argc, char *argv[]) { while (1) { static const struct option lopts[] = { { "device", 1, 0, 'D' }, { "speed", 1, 0, 's' }, { "delay", 1, 0, 'd' }, { "bpw", 1, 0, 'b' }, { "loop", 0, 0, 'l' }, { "cpha", 0, 0, 'H' }, { "cpol", 0, 0, 'O' }, { "lsb", 0, 0, 'L' }, { "cs-high", 0, 0, 'C' }, { "3wire", 0, 0, '3' }, { "no-cs", 0, 0, 'N' }, { "ready", 0, 0, 'R' }, { NULL, 0, 0, 0 }, }; int c; c = getopt_long(argc, argv, "D:s:d:b:lHOLC3NR", lopts, NULL); if (c == -1) break; switch (c) { case 'D': device = optarg; break; case 's': speed = atoi(optarg); break; case 'd': delay = atoi(optarg); break; case 'b': bits = atoi(optarg); break; case 'l': mode |= SPI_LOOP; break; case 'H': mode |= SPI_CPHA; break; case 'O': mode |= SPI_CPOL; break; case 'L': mode |= SPI_LSB_FIRST; break; case 'C': mode |= SPI_CS_HIGH; break; case '3': mode |= SPI_3WIRE; break; case 'N': mode |= SPI_NO_CS; break; case 'R': mode |= SPI_READY; break; default: print_usage(argv[0]); break; } } } int main(int argc, char *argv[]) { int ret = 0; int fd; parse_opts(argc, argv); fd = open(device, O_RDWR); if (fd < 0) pabort("can't open device"); /* * spi mode */ ret = ioctl(fd, SPI_IOC_WR_MODE, &mode); if (ret == -1) pabort("can't set spi mode"); ret = ioctl(fd, SPI_IOC_RD_MODE, &mode); if (ret == -1) pabort("can't get spi mode"); /* * bits per word */ ret = ioctl(fd, SPI_IOC_WR_BITS_PER_WORD, &bits); if (ret == -1) pabort("can't set bits per word"); ret = ioctl(fd, SPI_IOC_RD_BITS_PER_WORD, &bits); if (ret == -1) pabort("can't get bits per word"); /* * max speed hz */ ret = ioctl(fd, SPI_IOC_WR_MAX_SPEED_HZ, &speed); if (ret == -1) pabort("can't set max speed hz"); ret = ioctl(fd, SPI_IOC_RD_MAX_SPEED_HZ, &speed); if (ret == -1) pabort("can't get max speed hz"); printf("spi mode: %d\n", mode); printf("bits per word: %d\n", bits); printf("max speed: %d Hz (%d KHz)\n", speed, speed/1000); transfer(fd); close(fd); return ret; }
the_stack_data/126271.c
/* From: [email protected] To: [email protected] Subject: Re: Scary problems in g77 for RedHat 6.0. (glibc-2.1) Date: Sun, 06 Jun 1999 23:37:23 -0400 X-UIDL: 9c1e40c572e3b306464f703461764cd5 */ /* { dg-xfail-if "Can not call system libm.a with -msoft-float" { powerpc-*-aix* rs6000-*-aix* } { "-msoft-float" } { "" } } */ #include <stdio.h> #include <math.h> int main() { if (floor (0.1) != 0.) abort (); return 0; } /* It will result in 36028797018963968.000000 on Alpha RedHat Linux 6.0 using glibc-2.1 at least on my 21064. This may result in g77 bug reports concerning the INT() function, just so you know. Thanks, Rick Niles. */
the_stack_data/93887944.c
/* * Copyright (c) 2013 Jérémie Decock * * Usage: gcc string2.c * */ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char * argv[]) { /* ERROR: str is a constant string (in .rodata section, see objdump -s ...) * and cannot be modified */ //{ // char * str = "hello"; // str[0] = 'H'; // printf("%s\n", str); //} /* OK: the "proper" way to do it, str is dynamically allocated ("hello" is * in .rodata section, see objdump -s ...) */ { char * str = strdup("hello"); str[0] = 'H'; printf("%s\n", str); } /* OK: "hello" is in .text section (see objdump -s ...) but here str is * an "automatic" variable -> it is allocated in the stack */ //{ // char str[] = "hello"; // str[0] = 'H'; // printf("%s\n", str); //} exit(EXIT_SUCCESS); }
the_stack_data/1237749.c
#include <stdio.h> int main() { int numeros[50],j,total,i=0; int salir=0; while (salir!=1) { printf("\nIntroduzca un numero "); scanf("%d",&numeros[i]); i++; printf("\nPulse 1 para salir "); scanf("%d",&salir); } // Sumamos for (j=0;j<i;j++) total=total+numeros[j]; printf("\nEl resultado es %d\n\n",total); return 0; }
the_stack_data/247019433.c
#include<stdio.h> int main() { int i,j,k,n; printf("Enter Number : "); scanf("%d",&n); for(i=1;i<=n;i++) { for(j=1;j<=n;j++) { if(j <= (n+1-i)) { if(i==1 || j==1 || j == (n+1-i) ) printf("* "); else printf(" "); } } printf("\n"); } return 0; }
the_stack_data/17242.c
#include <stdio.h> #include <stdlib.h> int main() { char map[10] = { ' ', '.', '\'', ':', '~', '*', '=', ' ', '%', '#' }; FILE *finput = fopen("Exer_13_12_input.txt", "r"), *foutput = fopen("Exer_13_12_output.txt", "w"); if (finput == NULL || foutput == NULL) { printf("Can't open file.\n"); exit(EXIT_FAILURE); } int numbers[20][30]; for (int i = 0; i < 20; i++) for (int j = 0; j < 30; j++) fscanf(finput, "%d", &numbers[i][j]); char digits[20][31]; for (int i = 0; i < 20; i++) { for (int j = 0; j < 30; j++) digits[i][j] = map[numbers[i][j]]; digits[i][30] = '\0'; } for (int i = 0; i < 20; i++) fprintf(foutput, "%s\n", digits[i]); fclose(finput); fclose(foutput); return 0; }
the_stack_data/30504.c
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <assert.h> #include <unistd.h> typedef struct _account_t { int balance; pthread_mutex_t m; int aid; } account_t; typedef struct _transfer_args_t { account_t* from; account_t* to; int amount; } transfer_arg_t; void* deadlock_transfer(void *arg) { transfer_arg_t* tran = (transfer_arg_t*)(arg); printf("%d -> %d transfer $%d\n", tran->from->aid, tran->to->aid, tran->amount); pthread_mutex_lock(&tran->from->m); sleep(1); pthread_mutex_lock(&tran->to->m); tran->from->balance -= tran->amount; tran->to->balance += tran->amount; pthread_mutex_unlock(&tran->to->m); pthread_mutex_unlock(&tran->from->m); return NULL; } void create_account(account_t* acct, int balance) { static int aid = 0; acct->balance = balance; acct->aid = ++aid; pthread_mutex_init(&acct->m, NULL); } int main(int argc, char* argv[]) { pthread_t p1, p2; /* create two accounts */ account_t a1, a2; create_account(&a1, 1000); create_account(&a2, 1000); printf("main begin: a1's balance=%d, a2's balance=%d\n", a1.balance, a2.balance); /* create transfer arguments */ transfer_arg_t arg1, arg2; // arg1.from = &a1; arg1.to = &a2; arg1.amount = 100; // arg2.from = &a2; arg2.to = &a1; arg2.amount = 100; /* apply the two transactions */ if ( pthread_create(&p1, NULL, deadlock_transfer, &arg1) != 0 ) { fprintf(stderr, "pthread_create failed.\n"); exit(1); } if ( pthread_create(&p2, NULL, deadlock_transfer, &arg2) != 0 ) { fprintf(stderr, "pthread_create failed.\n"); exit(1); } assert( pthread_join(p1, NULL) == 0 ); assert( pthread_join(p2, NULL) == 0 ); printf("main end: a1's balance=%d, a2's balance=%d\n", a1.balance, a2.balance); pthread_mutex_destroy(&a1.m); pthread_mutex_destroy(&a2.m); return 0; }
the_stack_data/32951546.c
/* * pollSysfs.c - a poll(2) wrapper for Linux sysfs GPIO. * * Using poll(2) to wait for GPIO interrupts in Linux sysfs is a bit * flaky: * * - On certain combinations of kernels+hardware, a "dummy read(2)" is * needed before the poll(2) operation. As read(2) on a GPIO sysfs * pin's "value" attribute doesn't block, it doesn't hurt to do this * in all cases, anyway. * * - The Linux man page for poll(2) states that setting POLLERR in the * 'events' field is meaningless. However, the kernel GPIO * documentation states: "If you use poll(2), set the events POLLPRI * and POLLERR." Here we do what the kernel documentation says. * * - When poll(2) returns, an lseek(2) is needed before read(2), per * the Linux kernel documentation. * * - It appears that poll(2) on the GPIO sysfs pin's 'value' attribute * always returns POLLERR in 'revents', even if there is no error. * (This is supposedly true for all sysfs files, not just for GPIO.) * We simply ignore that bit and only consider the return value of * poll(2) to determine whether an error has occurred. (Presumably, * if POLLERR is set and poll(2) returns no error, then the * subsequent lseek(2) or read(2) will fail.) * * This module wraps poll(2) for use with Linux sysfs files by * accounting for these quirks. * * Ref: * https://e2e.ti.com/support/dsp/davinci_digital_media_processors/f/716/t/182883 * http://www.spinics.net/lists/linux-gpio/msg03848.html * https://www.kernel.org/doc/Documentation/gpio/sysfs.txt * http://stackoverflow.com/questions/16442935/why-doesnt-this-call-to-poll-block-correctly-on-a-sysfs-device-attribute-file * http://stackoverflow.com/questions/27411013/poll-returns-both-pollpri-pollerr */ #include <errno.h> #include <poll.h> #include <stdint.h> #include <unistd.h> /* * Poll a sysfs file descriptor for an event. * * As this function was written for the Haskell C FFI, and standard * practice is for Haskell timeouts/delays to be specified in * microseconds, the 'timeout' parameter is specified in microseconds. * However, poll(2)'s timeout argument is specified in milliseconds. * This function converts the specified microsecond timeout to * milliseconds before calling poll(2), but keep in mind that its * precision is therefore only millisecond-accurate. * * As with poll(2), if 'timeout' is negative, then the timeout is * disabled. * * This function may block, so when calling it from Haskell, you * should use the interruptible variant of the C FFI. Therefore, the * function may return EINTR and you should be prepared to re-try it * in this case. */ int pollSysfs(int fd, int timeout) { uint8_t dummy; if (read(fd, &dummy, 1) == -1) { return -1; } struct pollfd fds = { .fd = fd, .events = POLLPRI|POLLERR, .revents = 0 }; int timeout_in_ms = (timeout > 0) ? (timeout / 1000) : timeout; int poll_result = poll(&fds, 1, timeout_in_ms); if (poll_result == -1) { return -1; } if (lseek(fds.fd, 0, SEEK_SET) == -1) { return -1; } return poll_result; }