file
stringlengths
18
26
data
stringlengths
3
1.04M
the_stack_data/78636.c
#include <assert.h> typedef struct Foo { int a; int b; int c; } Foo; int main () { Foo foo1 = { .a = 1, .b = 2, .c = 3, }; assert (foo1.a == 1); assert (foo1.b == 2); assert (foo1.c == 3); Foo foo2 = { .b = 2, .a = 1, .c = 3, }; assert (foo2.a == 1); assert (foo2.b == 2); assert (foo2.c == 3); return 0; }
the_stack_data/243893444.c
/* * Filename: printf_EOF.c * Authro: Ge CHEN <[email protected]> * Date: 2015-02-01 * * exercise 1-7 * * Write a program to print the value of EOF. * */ #include <stdio.h> #include <stdlib.h> int main() { int c = EOF ; printf( "The value of 'EOF' is %d\n", c); return 0; }
the_stack_data/98370.c
/****************************************************************************** * * Copyright (c) 2020, 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: * * 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 OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * *****************************************************************************/ #include <argp.h> #include <stdarg.h> #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #include <unistd.h> #include <sys/time.h> #include <stdbool.h> #include <signal.h> #include <linux/ptp_clock.h> #include <poll.h> #include <fcntl.h> #include <pthread.h> #include <errno.h> #define BUFFER_SIZE 256 #define CLIENT_COUNT 2 #define DEFAULT_LISTENER_OUTFILE "tsq-listener-data.txt" #define NULL_OUTFILE "NULL" #define MODE_LISTENER 1 #define MODE_TALKER 2 int halt_sig; FILE *glob_fp; int glob_sockfd; int glob_ptpfd; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void error(char *msg, ...) { va_list argptr; if(glob_sockfd) close(glob_sockfd); if(glob_fp) fclose(glob_fp); if(glob_ptpfd) close(glob_ptpfd); va_start(argptr, msg); vfprintf(stderr, msg, argptr); va_end(argptr); exit(1); } /* Read shared signal variable */ int get_signal(void) { int temp = 0, ret = 0; ret = pthread_mutex_lock(&lock); if (ret) fprintf(stderr, "[TSQ] Failed to lock halt_sig.\n"); temp = halt_sig; ret = pthread_mutex_unlock(&lock); if (ret) fprintf(stderr, "[TSQ] Failed to unlock halt_sig.\n"); return temp; } /* Signal handler */ void sigint_handler(int signum) { int ret = 0; fprintf(stdout, "[TSQ] Thread exiting.\n"); ret = pthread_mutex_lock(&lock); if (ret) fprintf(stderr, "[TSQ] Failed to lock halt_sig.\n"); halt_sig = signum; ret = pthread_mutex_unlock(&lock); if (ret) fprintf(stderr, "[TSQ] Failed to unlock halt_sig.\n"); } typedef struct payload { int uid; int seq; long long secs; long nsecs; } payload; /* User input options */ struct opt { char *args[1]; int verbose; int mode; char *server_ip; long port; /* Listener */ char *output_file; /* Talker */ long uid; char *device; long timeout; }; static struct argp_option options[] = { /* Shared */ {"talker", 'T', 0, 0, "Talker mode (read AUXTS)"}, {"listener",'L', 0, 0, "Listener mode (listen for 2 talker and compare)"}, {"verbose", 'v', 0, 0, "Produce verbose output"}, {"ip", 'i', "ADDR", 0, "Server IP address (eg. 192.1.2.3)"}, {"port", 'p', "PORT", 0, "Port number\n" " Def: 5678 | Min: 999 | Max: 9999"}, /* Listener-specific */ {"output", 'o', "FILE", 0, "Save output to FILE (eg. temp.txt)"}, /* Talker-specific */ {"device", 'd', "FILE", 0, "PTP device to read (eg. /dev/ptp1)"}, {"uid", 'u', "COUNT", 0, "Unique Talker ID" " Def: 1234 | Min: 999 | Max: 9999"}, {"timeout", 't', "MSEC", 0, "Polling timeout in ms" " Def: 1100ms | Min: 1ms | Max: 2000ms"}, { 0 } }; static error_t parser(int key, char *arg, struct argp_state *state) { /* Get the input argument from argp_parse, which we */ /* know is a pointer to our user_opt structure. */ struct opt *user_opt = state->input; int len = 0; char *str_end = NULL; errno = 0; switch (key) { case 'v': user_opt->verbose = 1; break; case 'T': user_opt->mode = MODE_TALKER; break; case 'L': user_opt->mode = MODE_LISTENER; break; case 'i': user_opt->server_ip = arg; break; case 'p': len = strlen(arg); user_opt->port = strtol((const char *)arg, &str_end, 10); if (errno || user_opt->port <= 0 || user_opt->port < 999 || user_opt->port > 9999 || str_end != &arg[len]) error("Invalid port number. Check --help."); break; case 'o': user_opt->output_file = arg; break; case 'u': len = strlen(arg); user_opt->uid = strtol((const char *)arg, &str_end, 10); if (errno || user_opt->uid <= 0 || user_opt->uid < 999 || user_opt->uid > 9999 || str_end != &arg[len]) error("Invalid UID. Check --help."); break; case 'd': user_opt->device = arg; break; case 't': len = strlen(arg); user_opt->timeout = strtol((const char *)arg, &str_end, 10); if (errno || user_opt->timeout <= 0 || user_opt->timeout > 2000 || str_end != &arg[len]) error("Invalid timeout. Check --help."); break; default: return ARGP_ERR_UNKNOWN; } return 0; } static char usage[] = "-i <IP_ADDR> -p <PORT> -d /dev/ptp<X> -u <UID> {-T|-L}"; static char summary[] = "Time Sync Quality Measurement application"; static struct argp argp = { options, parser, usage, summary }; /** * @brief Validate payload structure received * * @param pl pointer to payload received * @param cli_ids * @return validation boolean result * */ bool validate_payload (payload *pl, int *cli_ids, int client_num) { bool ret = false; if ((pl->uid != 0) && (pl->secs != 0) && (pl->nsecs != 0)) { for (int i = 0 ; i < client_num ; i++) { if (cli_ids[i] == pl->uid) { ret = true; break; } } } return ret; } /** * @brief Check if all the data is received/ready for each client * * @param pl pointer to data ready flags table * @param size size of data ready flags table * @return true if data is now all available */ bool data_ready(bool *flags, int size) { for (int i = 0 ; i < size ; i++) { if (*flags == false) return false; flags++; } return true; } /** * @brief Reset data ready flags table * * @param pl pointer to data ready flags table * @param size size of data ready flags table */ void reset_data_ready(bool *flags, int size) { for (int i = 0; i < size; i++) { *flags = false; flags++; } } /* Listener - wait for 2 talkers to connect and receive. Compare both talker * timestamps to get the delta and transmit out. * TODO: Expand it to support 4 talkers at the same time? */ void listener(struct opt *user_opt) { char *server_ip; struct sockaddr_in serv; socklen_t len; int rounds = 0; int connfd = 0; int n = 0; int i = 0; int verbose; int max_sd = 0; int activity = 0; char recv_buff[BUFFER_SIZE]; long long secs_error; long nsecs_error; int cli_ids[CLIENT_COUNT]; int cli_conns[CLIENT_COUNT] = {}; payload cli_data[CLIENT_COUNT]; payload temp_data, keep_data; fd_set readfds; bool pl_valid_flag[CLIENT_COUNT] = {false, false}; bool skip_slot = false; int keep_data_slot = 0; memset(&keep_data, 0, sizeof(payload)); if(user_opt == NULL) error("[TSQ-L] User option is NULL"); verbose = user_opt->verbose; server_ip = user_opt->server_ip; glob_fp = fopen(user_opt->output_file, "w"); if (glob_fp == NULL) error("[TSQ-L] Error opening file: %s\n", user_opt->output_file); printf("[TSQ-L] Saving output in %s\n", user_opt->output_file); // Create listener socket glob_sockfd = socket(AF_INET, SOCK_STREAM, 0); if (glob_sockfd < 0) error("[TSQ-L] Error opening listening socket\n"); // connection settings memset(&serv, '0', sizeof(serv)); serv.sin_family = AF_INET; serv.sin_addr.s_addr = inet_addr(server_ip); if (user_opt->port != 0) serv.sin_port = htons(user_opt->port); else serv.sin_port = 0; // bind the socket and start listening if (bind(glob_sockfd, (struct sockaddr *)&serv, sizeof(serv)) < 0) error("[TSQ-L] Error binding listening socket\n"); listen(glob_sockfd, 2); len = sizeof(serv); if (getsockname(glob_sockfd, (struct sockaddr *)&serv, &len) == -1) error("[TSQ-L] getsockname() failed"); else if (verbose) printf("[TSQ-L] Started listening on %s:%d\n", server_ip, ntohs(serv.sin_port)); // Waiting for CLIENT_COUNT connections i = 0; while (i < CLIENT_COUNT && get_signal() == 0) { connfd = accept(glob_sockfd, (struct sockaddr *)NULL, NULL); if (connfd < 0) { printf("[TSQ-L] Error accepting connection. Waiting for the next one\n"); continue; } if (verbose) printf("[TSQ-L] Accept a connection. glob_sockfd[%d]:%d\n", i, connfd); bzero(recv_buff, BUFFER_SIZE); n = read(connfd, recv_buff, sizeof(recv_buff) - 1); if (n < 0) { //close the connection in case failed read close(connfd); error("[TSQ-L] ERROR reading UID from socket\n"); } cli_ids[i] = atoi(recv_buff); if (verbose) printf("[TSQ-L] Connected with client_id:%d\n", cli_ids[i]); cli_conns[i] = connfd; i++; } // clients connected. Send command to start broadcast for (int i = 0; i < CLIENT_COUNT; i++) { connfd = cli_conns[i]; bzero(recv_buff, BUFFER_SIZE); snprintf(recv_buff, sizeof(recv_buff), "start\n"); n = write(connfd, recv_buff, sizeof(recv_buff)); if (n < 0) error("[TSQ-L] Error writing to client socket.\n"); } memset(&cli_data, 0, sizeof(cli_data)); while (get_signal() == 0) { // write to file everytime fflush(glob_fp); FD_ZERO(&readfds); max_sd = 0; for (int i = 0; i < CLIENT_COUNT; i++) { FD_SET(cli_conns[i], &readfds); if (cli_conns[i] > max_sd) max_sd = cli_conns[i]; } /* * wait for an activity on one of the sockets , timeout is NULL, * so wait indefinitely */ activity = select(max_sd + 1, &readfds, NULL, NULL, NULL); if ((activity < 0) && (errno != EINTR)) error("[TSQ-L] Select error\n"); for (int i = 0; i < CLIENT_COUNT; i++) { bzero(recv_buff, BUFFER_SIZE); memset(&temp_data, '0', sizeof(temp_data)); connfd = cli_conns[i]; if (FD_ISSET(connfd, &readfds)) { if (get_signal() != 0) error("[TSQ-L] client socket closed. TSQ will end now.\n"); n = read(connfd, recv_buff, sizeof(recv_buff) - 1); if (n < 0) error("[TSQ-L] ERROR reading socket. Exiting.\n"); /* * If the slot is marked for keeping for sample alignment * we will recopy the previous value and not use the one read from the socket. */ if ((skip_slot == true) && (keep_data_slot == i)) { memcpy(&cli_data[i], &keep_data, sizeof(payload)); pl_valid_flag[i] = true; /* * if (verbose) * printf("[TSQ-L] KEEP SLOT data from %d : Secs : %lld, Nsecs : %ld , seq : %d\n", * cli_data[i].uid, cli_data[i].secs, cli_data[i].nsecs , cli_data[i].seq); */ } else { if (n > 0) { // copy the new value memcpy(&temp_data, recv_buff, sizeof(payload)); if (validate_payload (&temp_data, cli_ids, CLIENT_COUNT)) { pl_valid_flag[i] = true; memcpy(&cli_data[i], &temp_data, sizeof(payload)); /*if (verbose) printf("[TSQ-L] Msg from %d : Secs : %lld, Nsecs : %ld , seq : %d\n", cli_data[i].uid, cli_data[i].secs, cli_data[i].nsecs, cli_data[i].seq); */ } } } } } if (data_ready(pl_valid_flag, CLIENT_COUNT)) { secs_error = cli_data[0].secs - cli_data[1].secs; nsecs_error = cli_data[0].nsecs - cli_data[1].nsecs; if (verbose) printf("[TSQ-L] Msg from %d, %d: Secs off: %lld, Nsecs off: %ld\n", cli_data[0].uid, cli_data[1].uid, secs_error, nsecs_error); /* * 1. When secs_error is equals to 1, t0 sample is 'newer' compared to t1. * This means the t0 sample is not align to t1 sample, we shd keep t0, discard current t1, and reread t1. * 2. When secs_error is equals to -1, t1 sample is now 'newer' compare to t0. * The t1 sample is not align to t0 sample, we shd keep t1, discard current t0, and reread t0. * 3. When secs_error is 0 , the samples are aligned. The nsecs is then valid. * 4. When secs_error are not ( 0 | 1 |-1) , the samples are misaligned , and we wait for alignment in future samples. * In this case, we discard nsecs_errors. */ switch (secs_error) { case 1: skip_slot = true; keep_data_slot = 0; memcpy(&keep_data, &cli_data[0], sizeof(payload)); break; case -1: skip_slot = true; keep_data_slot = 1; memcpy(&keep_data, &cli_data[1], sizeof(payload)); break; case 0: skip_slot = false; memset(&keep_data, '0', sizeof(payload)); fprintf(glob_fp, "%d %lld %ld\n", rounds, secs_error, nsecs_error); rounds++; break; default: skip_slot = false; memset(&keep_data, '0', sizeof(payload)); printf("[TSQ-L] Waiting for samples alignment...\n"); break; } reset_data_ready(pl_valid_flag, CLIENT_COUNT); memset(&cli_data, 0, sizeof(cli_data)); } } close(glob_sockfd); fclose(glob_fp); } void talker(struct opt *user_opt){ char *server_ip; int verbose; int uid; int port; struct sockaddr_in serv; char send_buff[BUFFER_SIZE]; int n; payload data; int seq = 0; char *device; int timeout_ms; struct pollfd pfd; struct ptp_extts_event e; int ready; int ret; if(user_opt == NULL) error("[TSQ-T] User option is NULL"); server_ip = user_opt->server_ip; port = user_opt->port; device = user_opt->device; verbose = user_opt->verbose; uid = user_opt->uid; glob_sockfd = 0; if (verbose) printf("[TSQ-T] Assigned uid %d\n", uid); /* Set up the socket for transmission */ memset(&serv, '0', sizeof(serv)); serv.sin_family = AF_INET; serv.sin_addr.s_addr = inet_addr(server_ip); serv.sin_port = htons(port); glob_sockfd = socket(AF_INET, SOCK_STREAM, 0); if (glob_sockfd < 0) error("[TSQ-T] Could not create socket\n"); if (connect(glob_sockfd, (struct sockaddr *)&serv, sizeof(serv)) < 0) error("[TSQ-T] Connect Failed\n"); if (verbose) printf("[TSQ-T] Connection established with %s\n", server_ip); bzero(send_buff, BUFFER_SIZE); // send uid snprintf(send_buff, sizeof(send_buff), "%d\n", uid); ret = write(glob_sockfd, send_buff, sizeof(send_buff)); if (ret < 0) error("[TSQ-T] ERROR writing UID to socket\n"); if (verbose) printf("[TSQ-T] Sent %s to tsq-listener\n", send_buff); bzero(send_buff, BUFFER_SIZE); n = read(glob_sockfd, send_buff, sizeof(send_buff) - 1); if (n < 0) error("[TSQ-T] ERROR reading command from socket\n"); if (strcmp(send_buff, "start\n") != 0) error("[TSQ-T] Connection aborted\n"); if (verbose) printf("[TSQ-T] Reading from %s\n", device); glob_ptpfd = open(device, O_RDWR); if (glob_ptpfd < 0) error("[TSQ-T] ERROR to open ptp device %s\n", device); if (verbose) printf("[TSQ-T] PTP device : %s is now opened\n", device); pfd.fd = glob_ptpfd; pfd.events = PTP_PF_EXTTS; pfd.revents = 0; timeout_ms = user_opt-> timeout; if (verbose) printf("[TSQ-T] Setting timeout to %dms\n", timeout_ms); while (get_signal() == 0) { ready = poll(&pfd, 1, timeout_ms); if (ready < 0) error("[TSQ-T] Failed to poll\n"); e.t.sec = 0; e.t.nsec = 0; while (ready-- > 0) { n = read(glob_ptpfd, &e, sizeof(e)); if (n != sizeof(e)) { error("[TSQ-T] read returns %lu bytes, expecting %lu bytes\n", n, sizeof(e)); } } data.uid = uid; data.seq = seq; data.secs = e.t.sec; data.nsecs = e.t.nsec; bzero(send_buff, BUFFER_SIZE); memcpy(send_buff, &data, sizeof(data)); /* * If secs / nsecs turns out to be zero, it wont be sent over, * because the values read are not valid. */ if ( (data.secs != 0) && (data.nsecs != 0) ) { if (verbose) printf("[TSQ-T:%d] Sending %d: %lld#%ld\n", uid, seq, data.secs, data.nsecs); ret = write(glob_sockfd, send_buff, sizeof(send_buff)); if (ret < 0) error("[TSQ-T] Erorr writing to socket.\n"); seq++; } else { if (verbose) printf ("[TSQ-T] sec:%lld nsec:%ld seq: %d\n", data.secs, data.nsecs, seq); } } close(glob_sockfd); } int main(int argc, char *argv[]) { struct opt user_opt; /* Defaults */ user_opt.mode = 0; user_opt.verbose = 0; user_opt.device = "\0"; user_opt.timeout = 1100; // ms user_opt.uid = 1234; user_opt.port = 5678; user_opt.output_file = DEFAULT_LISTENER_OUTFILE; glob_fp = NULL; glob_ptpfd = -1; halt_sig = 0; argp_parse(&argp, argc, argv, 0, 0, &user_opt); signal(SIGINT, sigint_handler); signal(SIGTERM, sigint_handler); signal(SIGABRT, sigint_handler); switch(user_opt.mode){ case MODE_TALKER: /* IP, PORT, UID, device */ talker(&user_opt); break; case MODE_LISTENER: /* IP (itself), PORT*/ listener(&user_opt); break; default: error("Invalid mode selected\n"); break; } return 0; }
the_stack_data/140764930.c
// hw02_03.c #include <stdio.h> #include <stdlib.h> int main(void){ int n1, n2, DAYSPERYEAR; DAYSPERYEAR = 365; n1 = 26; n2 = 33; printf("%d years = %d days\n", n1, n1 * DAYSPERYEAR); printf("%d years = %d days\n", n2, n2 * DAYSPERYEAR); system("pause"); return 0; } /* 26 years = 9490 days 33 years = 12045 days Press any key to continue . . . */
the_stack_data/143172.c
#include <stddef.h> wchar_t a() { return L'\u37D0'; }
the_stack_data/104829042.c
// Copyright 2021 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> void burn_cgo() { while (1) asm(""); } static void *burn_pthread(void *arg) { while (1) asm(""); } static void *burn_pthread_go(void *arg) { extern void burn_callback(void); burn_callback(); } void prep_cgo() { burn_cgo(); } void prep_pthread() { int res; pthread_t tid; res = pthread_create(&tid, NULL, burn_pthread, NULL); if (res != 0) { fprintf(stderr, "pthread_create: %s\n", strerror(res)); exit(EXIT_FAILURE); } } void prep_pthread_go() { int res; pthread_t tid; res = pthread_create(&tid, NULL, burn_pthread_go, NULL); if (res != 0) { fprintf(stderr, "pthread_create: %s\n", strerror(res)); exit(EXIT_FAILURE); } }
the_stack_data/225142644.c
/* lc461.c */ /* LeetCode 461 Hamming Distance `E` */ /* A~0b19 */ /* acc | 29' | rt53%* | mu70% */ int hammingDistance(int x, int y) { int res = x ^ y; int cnt = 0; for (int i = 0; i < 31; i++) { if (res & 1) cnt++; res >>= 1; } return cnt; }
the_stack_data/979515.c
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include <stdio.h> void c2(void) { puts("c2"); }
the_stack_data/11075546.c
typedef struct { long i; double f; } T; f (T *n1, T *n2) { if (g (n2)) return n1->i - n2->i; else { double f = n1->f - n2->i; return f == 0.0 ? 0 : (f > 0.0 ? 1 : -1); } }
the_stack_data/15762029.c
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { printf("Hello There\n"); // Taking user input char *name = calloc(50, sizeof(char)); printf("Enter your name: "); gets(name); // Length of the string int length = strlen(name); printf("%i\n", length); // Pointer Arithmetic for (int i = 0; i < length; i++) { printf("%p \t %i \t %c\n", (name + i), *(name + i), *(name + i)); } free(name); return 0; }
the_stack_data/434221.c
#include <stdio.h> #include <pthread.h> #include <unistd.h> #include <stdlib.h> #include <semaphore.h> int buf[2]; sem_t write_buf_0; sem_t write_buf_1; sem_t write_buf; sem_t take_for_cal; sem_t ready_for_cal; sem_t check_write_0; sem_t check_write; int have_data_0; int have_data_1; int get_sem_val(sem_t * sem){ int sval; sem_getvalue(sem, &sval); return sval; } void * write_0(){ // FILE * fp = fopen("1.dat", "r"); // if(!fp){ // printf("File \"1.dat\" opening failed"); // return (void *)0; // } int data_set[] = {1,2,3,4,5,6,7,8,9,10}; for(int i = 0; i < 10; i++){ have_data_0 = 1; // printf("w_1 in working\n"); int temp = data_set[i]; // printf("write 0 Round %d want write_b\n", i); sem_wait(&write_buf); // printf("write 0 Round %d get write_b\n", i); // printf("write 0 Round %d want check_write\n", i); sem_wait(&check_write_0); // printf("write 0 Round %d get check_write\n", i); if(get_sem_val(& write_buf_0)){ sem_wait(&write_buf_0); // printf("write 0 Round %d get write_buf_0\n", i); buf[0] = temp; } else{ sem_wait(&write_buf_1); // printf("write 0 Round %d get write_buf_1\n", i); buf[1] = temp; } sem_post(&check_write_0); // printf("write 0 round %d release check_write_0 \n", i); sem_wait(&check_write); // printf("write 0 round %d get check_write \n", i); if(get_sem_val(&write_buf) == 0){ sem_post(&ready_for_cal); // printf("write 0 round %d release ready_for_cal \n", i); sem_post(&take_for_cal); // printf("write 0 round %d release takeforcal \n", i); } sem_post(&check_write); // printf("write 0 round %d release check_write \n", i); // if(temp == 10 || temp == -10){ // break; // } } have_data_0 = 0; return (void *) 0; } void * write_1(){ // FILE * fp = fopen("1.dat", "r"); // if(!fp){ printf("File \"1.dat\" opening failed"); // return (void *)0; // } int data_set[] = {-1, -2, -3, -4, -5, -6, -7, -8, -9, -10}; for(int i = 0; i < 10; i++){ // printf("w_1 in working\n"); int temp = data_set[i]; // printf("write 1 Round %d want write_b\n", i); sem_wait(&write_buf); // printf("write 1 Round %d get write_b\n", i); // printf("write 1 Round %d want check_write\n", i); sem_wait(&check_write_0); // printf("write 1 Round %d get check_write\n", i); if(get_sem_val(& write_buf_0)){ sem_wait(&write_buf_0); // printf("write 1 Round %d get write_buf_0\n", i); buf[0] = temp; } else{ sem_wait(&write_buf_1); // printf("write 1 Round %d get write_buf_1\n", i); buf[1] = temp; } sem_post(&check_write_0); // printf("write 1 round %d release check_write_0 \n", i); sem_wait(&check_write); // printf("write 1 round %d get check_write \n", i); if(get_sem_val(&write_buf) == 0){ sem_post(&ready_for_cal); // printf("write 1 round %d release ready_for_cal \n", i); sem_post(&take_for_cal); // printf("write 1 round %d release takeforcal \n", i); } sem_post(&check_write); // if(temp == 10 || temp == -10){ // break; // } // printf("write 1 round %d release check_write \n", i); } return (void *) 0; } void * AddFun(){ while(1){ // printf("add want ready_for_cal\n"); sem_wait(&ready_for_cal); // printf("add get ready_for_cal\n"); // printf("add want take_for_cal\n"); sem_wait(&take_for_cal); // printf("add get take_for_cal\n"); int temp_0 = buf[0]; int temp_1 = buf[1]; printf("%d + %d = %d\n", temp_0, temp_1, temp_0 + temp_1); sem_post(&take_for_cal); // printf("add released takeforcal\n"); sem_post(&write_buf_0); // printf("add release write_buf_0\n"); sem_post(&write_buf); // printf("add release write_buf\n"); sem_post(&write_buf_1); // printf("add release write_buf_1\n"); sem_post(&write_buf); // printf("add release write_buf\n"); } return (void *) 0; } void * MulFun(){ while(1){ // printf("mul want ready_for_cal\n"); sem_wait(&ready_for_cal); // printf("mul get ready_for_cal\n"); // printf("mul want take_for_cal\n"); sem_wait(&take_for_cal); // printf("mul get take_for_cal\n"); int temp_0 = buf[0]; int temp_1 = buf[1]; printf("%d * %d = %d\n", temp_0, temp_1, temp_0 * temp_1); sem_post(&take_for_cal); // printf("mul released takeforcal\n"); sem_post(&write_buf_0); // printf("mul release write_buf_0\n"); sem_post(&write_buf); // printf("mul release write_buf\n"); sem_post(&write_buf_1); // printf("mul release write_buf_1\n"); sem_post(&write_buf); // printf("mul release write_buf\n"); } return (void *) 0; } int main(int argc, char const *argv[]){ /* code */ have_data_0 = have_data_1 = 1; sem_init(&write_buf_0, 0, 1); sem_init(&write_buf_1, 0, 1); sem_init(&write_buf, 0, 2); sem_init(&take_for_cal, 0, 0); sem_init(&ready_for_cal, 0, 0); sem_init(&check_write_0, 0, 1); sem_init(&check_write, 0, 1); printf("ready_for_cal: %d\n", get_sem_val(&ready_for_cal)); pthread_t id_write_0; pthread_t id_write_1; pthread_t id_AddFun; pthread_t id_MulFun; pthread_create(&id_write_0, NULL, (void *)write_0, NULL); pthread_create(&id_write_1, NULL, (void *)write_1, NULL); pthread_create(&id_AddFun, NULL, (void *)AddFun, NULL); pthread_create(&id_MulFun, NULL, (void *)MulFun, NULL); pthread_join(id_write_0, NULL); pthread_join(id_write_1, NULL); pthread_join(id_AddFun, NULL); pthread_join(id_MulFun, NULL); return 0; }
the_stack_data/92407.c
/* * Copyright 2020 The Emscripten Authors. All rights reserved. * Emscripten is available under two separate licenses, the MIT license and the * University of Illinois/NCSA Open Source License. Both these licenses can be * found in the LICENSE file. */ #include <stdint.h> #include <stdlib.h> #include <setjmp.h> // 0 - Nothing thrown // 1 - Exception thrown // Other values - jmpbuf pointer in the case that longjmp was thrown static uintptr_t setjmpId = 0; typedef struct TableEntry { uintptr_t id; uint32_t label; } TableEntry; extern void setTempRet0(uint32_t value); extern void setThrew(uintptr_t threw, int value); extern void _emscripten_throw_longjmp(); // defined in src/library.js TableEntry* saveSetjmp(uintptr_t* env, uint32_t label, TableEntry* table, uint32_t size) { // Not particularly fast: slow table lookup of setjmpId to label. But setjmp // prevents relooping anyhow, so slowness is to be expected. And typical case // is 1 setjmp per invocation, or less. uint32_t i = 0; setjmpId++; *env = setjmpId; while (i < size) { if (table[i].id == 0) { table[i].id = setjmpId; table[i].label = label; // prepare next slot table[i + 1].id = 0; setTempRet0(size); return table; } i++; } // grow the table size *= 2; table = (TableEntry*)realloc(table, sizeof(TableEntry) * (size +1)); table = saveSetjmp(env, label, table, size); setTempRet0(size); // FIXME: unneeded? return table; } uint32_t testSetjmp(uintptr_t id, TableEntry* table, uint32_t size) { uint32_t i = 0; while (i < size) { uintptr_t curr = table[i].id; if (curr == 0) break; if (curr == id) { return table[i].label; } i++; } return 0; } void emscripten_longjmp(uintptr_t env, int val) { setThrew(env, val); _emscripten_throw_longjmp(); }
the_stack_data/12637137.c
#include <stdio.h> #include <stdbool.h> int main() { while (true) { //Entry Section //Critical Section //Exit Section //Remainder Section } return 0; }
the_stack_data/55607.c
#include <stdio.h> long getPosition(int depth, long index) { long node = 1; /* top node */ --index; /* make index zero-based */ long i; for (i = 0; i < depth - 1; ++i) /* go down the tree (depth-1) times */ { node *= 2; /* go down one node*/ if (index % 2 == 1) /* right subtree if not divisible by 2*/ { ++node; } index /= 2; } return node; } void testGetPosition(int depth, long index, long expected) { long actual = getPosition(depth, index); printf("%li: expected %li, got %li.\n", index, expected, actual); } int main() { /* testGetPosition(4, 1, 8); testGetPosition(4, 2, 12); testGetPosition(4, 3, 10); return 0; */ int depth; /* 2 <= d <= 20 */ long index; /* 1 <= i <= 524288 */ int numTestCases, i; scanf("%d", &numTestCases); for (i = 0; i < numTestCases; ++i) { scanf("%d %ld", &depth, &index); long answer = getPosition(depth, index); printf("%ld\n", answer); } return 0; }
the_stack_data/72141.c
#include <math.h> extern int japply; gtjul2(eqxin,ra,dec,tobsin,ieflg,raout,decout) int ieflg; double eqxin,ra,dec,tobsin,*raout,*decout; { /* * 31jul92 - changes to jrmvet,jaddet; substituted more general purpose * subs jgtobq,ecleqx,equec2 for limited- purpose subs gtoblq,ecleq2,equec2 * 23jul92 to call nwcprc/nwcprp instead of jprecj. * 02jul92 - re; routines with propermotions: * gtjulp will assume eqx,epoch B1950 in and yield eqx,epoch J2000 out. * unjulp will assume eqx,epoch J2000 in and yield eqx,epoch B1950 out. * 30jun92 to apply fk5-fk4 sys. corr. to eqx B1950 position before any other * corrections. * 05,06mar92 to use astron. suppl 1984 & 1961 e-term removal equations * (in subs gtjul2,gtjulp,unjul,unjulp) * 13-15jan92 updated to reflect method described in FK5 Part I. Catalog * author: judy bennett * * to precess old besselian equinox positions to equator and equinox of * J2000.0. * * Calls subroutines nwcprc ("old" Newcomb constants) and fk5prc and fk5prp * ("new" Julian prcession formulas). * * Source of method: * Fifth Fundamental Catalogue (FK5) Part I (1988, but not avail. till 1992) * Section 8. (page 9) * Summary of order: * 1. Precess each object (using precessional values adopted in that cat- * i.e. usually Newcomb) from the catalogue equinox to the mean equinox * at the object's mean epoch (i.e. observation date). * 2. The mean positions in all star catalogues published prior to 1984 * contain the terms of elliptic aberration (E-terms). These terms need * to be removed from the star's mean position. * 3. The equinox correction and the systematic correction FK5-FK4 * (given in the FK5 cat), computed for the object's mean epoch, need to * be applied. Note: program applies fk5-fk4 sys.corr. at B1950 which * seems consistent with procedure actually described in the FK5. * 4. The corrected position has to be precessed to the new standard equinox * J2000.0 using the precessional quantities as adopted in the IAU(1976) * System of Astronomical Constants (also see Astronomical Almanac 1984, * pages S34,S36) * * NOTE: these routines apply the fk5-fk4 correction at B1950. * if no fk5-fk4 systematic correction required, the user should * include the following statements in his program: * (a value of 0 for japply specifies no corrections; anything else uses corr.) * external jfk5bd * common /fkappl/ japply * japply = 0 * * **************************************************************************** * All arguments are double precision, except ieflg which is integer. * Input values: * eqxin is the equinox of the input position (if negative, absolute val.used) * ra is right ascension (decimal degrees) at eqx * dec is declination (decimal degrees) at eqx * tobsin is the year of observation (i.e. when the object was observed at * this position (e.g. 1983.5d0) ; if 0.0d0, value of eqxin is used. * ieflg is flag allowing removal of E-terms of aberration if any (usually * they are present, therefore ieflg should = +1): * ieflg = -1 do not remove E-terms (there none). * ieflg = any value except -1 indicates E-terms are present and * are to be removed. * Returned values: * raout is right ascension at equator and equinox of J2000.0 * decout is declination at equator and equinox of J2000.0 * * **************************************************************************** * * Files required: gtjul2.f (includes gtjul2,gtjulp,unjul2,unjulp,gtecle, * gtetrm,itere,iterec,jaddet,jclpos,jrmvet) * ecleqx.f (includes ecleqx,equecx,jgtobq) * fk5prc.f (includes fk5prc,fk5prp) * nwcprc.f (includes nwcprc,nwcprp) * jgtfkc.f (includes jgtfkc,junfkc,jnitfk.jfk5bd,dintrp,dintr2) * * **************************************************************************** */ double tobs, tobsj, jde, eqx, rat50, dect50; double rat, dect, delt, dela; double corra, corrd, corrpa, corrpd; eqx = fabs(eqxin); tobs = fabs(tobsin); if(tobs == 0.0) tobs = eqx; if(japply == 0) { rat50 = ra; dect50 = dec; } else { /* determine fk5-fk4 systematic correction using eqx B1950 postion */ if(eqx != 1950.0) nwcprc(eqx,ra,dec,1950.0,&rat50,&dect50); else { rat50 = ra; dect50 = dec; } jgtfkc(rat50,dect50,0.0,tobs,&corra,&corrd,&corrpa,&corrpd); rat50 = rat50 + corra; dect50 = dect50 + corrd; jclpos(&rat50,&dect50); eqx = 1950.0; } if (tobs != eqx) /* use old newcomb formula to prec. to tobs */ nwcprc( eqx, rat50, dect50, tobs, &rat, &dect); else { rat = rat50; dect = dect50; } /* * compute the correction for right ascension at the mean epoch of observations. * note: this correction will generally be of order +0.06s for most modern * catalogs. * delt is fraction of Julian century; adjust tobs in besselian time frame * to be correct * in terms of Julian. use jde of b1950 and tropical year in days * to get Julian day of observations. Then compute equivalent year for * Julian prec. prog. so fraction of Julian year will be correct. * B1950 = JDE 2433282.4235 365.2421988 tropical days per year. * J2000 = JDE 2451545.00 365.25 Julian days per year. * */ jde = ((tobs - 1950.0) * 365.2421988) + 2433282.4235; tobsj = 2000.0 + ((jde - 2451545.0)/365.25); /* * Remove E-terms if necessary: */ if(ieflg != -1) jrmvet(tobsj,&rat,&dect); /* * Apply the equinox correction (use tobs not tobsj): * */ delt = (tobs - 1950.0) * 0.01; dela = ((0.035 + 0.085*delt) * 15.0) / 3600.0; rat = rat + dela; jclpos(&rat,&dect); /* * now compute mean place of source at 2000 Jan. 1.5 using the mean place * at the mean epoch of observations tobs (with dela applied) and the * new precession formulas (i.e. Julian prec. formulas) * */ fk5prc( tobsj, rat, dect, 2000.0, raout, decout); } unjul2(rain,decin,tobsin,ieflg,eqxbou,raout,decout) int ieflg; double rain,decin,tobsin,eqxbou,*raout,*decout; { /* * author: judy bennett * 01jul92 * 26jun92 to allow removal of fk5-fk4 systematic corrections * 17jan92 * 05feb92 to use fk5prc instead of hcprec. * * unjul2 reverses what gtjul2 did - i.e. unjul2 precesses accurately * back to the original besselian input. * * to precess new Julian equinox positions (J2000.0)back to input besselian * equinox positions (B1950.0). * * Calls subroutines nwcprc ("old" Newcomb constants) and fk5prc ("new" * Julian prec.formulas). * * Source of method: * See comments in gtjul2. * * **************************************************************************** * All arguments are double precision, except ieflg which is integer. * Input values: * rain is right ascension (decimal degrees) at J2000.0 * decin is declination (decimal degrees) at J2000.0 * tobsin is the year of observation (i.e. when the object was assigned this pos) * if 0.0d0, eqxbou is used. * ieflg is flag allowing restore of E-terms of aberration if any (usually * they are present; ieflg should usually = + 1). * ieflg =-1 do not replace E-terms (there none). * ieflg = anything but -1 indicates E-terms are to be present * and are to be replaced. Usually they are to be replaced. * eqxbou is output equinox (besselian): if 0.0d0, 1950.0d0 is used. * Returned values: * raout is right ascension at besselian equinox of eqxbou. * decout is declination at besselian equinox of eqxbou. * * **************************************************************************** */ double ra, dec; double tobsj, jde, tobsb; double rat, dect, delt, dela; double eqx1=2000.0,eqx2,rat50,dect50; double corra, corrd, corrpa, corrpd; if(eqxbou != 0.0) eqx2 = fabs(eqxbou); else eqx2 = 1950.0; if(tobsin != 0.0) tobsb = fabs(tobsin); else tobsb = eqx2; ra = rain; dec = decin; /* * tobsj is year in terms of Julian years; tobsb is year in terms of tropical. * */ jde = ((tobsb - 1950.0) * 365.2421988) + 2433282.4235; tobsj = 2000.0 + ((jde - 2451545.0)/365.25); fk5prc( eqx1, ra, dec, tobsj, &rat, &dect); /* * remove the equinox correction (use tobsb not tobsj): * */ delt = (tobsb - 1950.0) * 0.01; dela = ((0.035 + 0.085*delt) * 15.0) / 3600.0; rat = rat - dela; if(rat >= 360.0) rat = rat - 360.0; if(rat < 0.0) rat = rat + 360.0; /* * Add back E-terms if necessary: */ if(ieflg != -1) jaddet(tobsj,&rat,&dect); if(japply == 0) { if(tobsb != eqx2) nwcprc( tobsb,rat, dect, eqx2, raout, decout); else { *raout = rat; *decout = dect; } } else { /* find and remove fk5-fk4 systematic corrections: */ if(tobsb == 1950.0) { rat50 = rat; dect50 = dect; } else nwcprc(tobsb,rat,dect,1950.0,&rat50,&dect50); junfkc(rat50,dect50,0.0,tobsb,&corra,&corrd,&corrpa,&corrpd); rat50 = rat50 - corra; dect50 = dect50 - corrd; jclpos(&rat50,&dect50); if(eqx2 != 1950.0) nwcprc(1950.0,rat50,dect50,eqx2,raout,decout); else { *raout = rat50; *decout = dect50; } } return 0; } gtjulp(eqxin,rain,decin,pmain,pmdin,pin,vin,ieflg, raout,decout,pmaout,pmdout) int ieflg; double eqxin,rain,decin,pmain,pmdin,pin,vin, *raout,*decout,*pmaout,*pmdout; { /* * 27jul92 to allow pmain,pmdin =0.0d0 to be processed as any other * source with given proper motions (User must use gtjul2 * if proper motions are "intrinsically" zero (e.g. radio source) * or if no proper motions are given for the object). * 02jul92 to apply fk5-fk4 systematic corrections at B1950. * eqxin will be ignored; jgtjulp assumes equinox,epoch B1950 for inputs. * 24jun92 to apply fk5-fk4 systematic corrections if desired. * 05feb92 like gtjul2, except for objects with proper motions etc. * * author: judy bennett * * to precess old besselian equinox positions to equator, equinox and epoch * of J2000.0. * * Source of method: * Fifth Fundamental Catalogue (FK5) Part I (1988, but not avail. till 1992) * Section 8. (page 9) + discussion in FK5 * * **************************************************************************** * All arguments are double precision, except ieflg which is integer. * Input values: * eqxin is ignored (assumes 1950.0d0); * is the equinox & epoch of input position * rain is right ascension (decimal degrees) at equinox & epoch of B1950 * decin is declination (decimal degrees) at equinox & epoxh of B1950 * pmain is proper motion in ra in seconds of time per tropical century * pmdin is proper motion in dec in seconds of arc per tropical century * pin is parallax in arc seconds. * vin is radial velocity in km/sec * ieflg is flag allowing removal of E-terms of aberration if any (usually * E-terms are present; therefore, ieflg should = +1) * ieflg = -1 do not remove E-terms (there none). * ieflg = anything except -1 indicates E-terms are present and * are to be removed. * Returned values: * raout is right ascension at epoch, equator and equinox of J2000.0 * decout is declination at epoch, equator and equinox of J2000.0 * pmaout is proper motion in seconds of time per Julian century. * pmdout is proper motion in seconds of arc per Julian century. * * **************************************************************************** * */ double pma, pmd, corra, corrd, corrpa, corrpd; double tobs=1950.0, tobsj, jde, eqx = 1950.0; double rar,decr, work; double rat, dect, delt, dela; double pmat, pmdt, dtor; dtor = atan(1.0) / 45.0; if(japply == 0) { rat = rain; dect = decin; pma = pmain; pmd = pmdin; } else /* determine fk5-fk4 correction & apply */ { rat = rain; dect = decin; jgtfkc(rat,dect,0.0,tobs,&corra,&corrd,&corrpa,&corrpd); rat = rat + corra; dect = dect + corrd; jclpos(&rat,&dect); pma = pmain + corrpa; pmd = pmdin + corrpd; } /* * compute the correction for right ascension at the mean epoch of observations. * note: this correction will generally be of order +0.06s for most modern * catalogs. * delt is fraction of Julian century; adjust tobs in besselian time frame * to be correct * in terms of Julian. use jde of b1950 and tropical year in days * to get Julian day of observations. Then compute equivalent year for * Julian prec. prog. so fraction of Julian year will be correct. * B1950 = JDE 2433282.4235 365.2421988 tropical days per year. * J2000 = JDE 2451545.00 365.25 Julian days per year. * */ jde = ((tobs - 1950.0) * 365.2421988) + 2433282.4235; tobsj = 2000.0 + ((jde - 2451545.0)/365.25); /* * * Remove E-terms if necessary: */ if(ieflg != -1) jrmvet(tobsj,&rat,&dect); /* * Apply the equinox correction (use tobs not tobsj): * equinox correction from fk5 cat (Section 3 (page 6). */ delt = (tobs - 1950.0) * 0.01; dela = ((0.035 + 0.085*delt) * 15.0) / 3600.0; rat = rat + dela; jclpos(&rat,&dect); /* * convert proper motions from units per tropical century to units per Julian * century per p.S35 of Supp. to Astron.Alman. * apply time-dependent portion of eqx corr to ra proper motion (0.0850 secs of * time per Julian century) per FK5 Catalog (Section 3 (page 6)). * also adjust for change in precession constant per p. S35 of Supp. to * Astron. Alman. (note; misprint in Supp.: 0.6912 should be 0.06912) * */ rar = rat*dtor; decr = dect*dtor; if(fabs(dect) > 89.9999) work = 0.0; else work = 0.0291*sin(rar)*tan(decr); pmat = (pma * 1.00002136) - 0.06912 - work + 0.0850; pmdt = (pmd * 1.00002136) - 0.436*cos(rar); /* * now compute mean place of source at 2000 Jan. 1.5 using the mean place * at at the mean epoch of observations tobs (with dela applied) and the * new precession formulas (i.e. Julian prec. formulas) * * */ fk5prp( tobsj, rat, dect, pmat, pmdt, pin, vin, 2000.0, raout, decout, pmaout, pmdout); return 0; } unjulp(rain,decin,pmain,pmdin,pin,vin,ieflg, eqxbou,raout,decout,pmaout,pmdout) int ieflg; double rain,decin,pmain,pmdin,pin,vin, eqxbou,*raout,*decout,*pmaout,*pmdout; { /* * 27jul92 to allow pmain,pmdin =0.0d0 to be processed as any other * source with given proper motions (User must use unjul2 * if proper motions are "intrinsically" zero (e.g. radio source) * or if no proper motions are given for the object). * 02jul92-eqxbou is ignored (assumed to be equinox,epoch B1950.0d0 for outputs) * 26jun92 to allow removal for fk5-fk4 correction. * author: judy bennett * * unjulp reverses what gtjulp did - i.e. unjulp precesses accurately * back to the original besselian input ( B1950). * * to precess new Julian equinox positions (J2000.0)back to input besselian * equinox positions (B1950.0). * * Source of method: * See comments in gtjul2. * * **************************************************************************** * All arguments are double precision, except ieflg which is integer. * Input values: * rain is right ascension (decimal degrees) at epoch & equinox of J2000.0 * decin is declination (decimal degrees) at epoch & equinox of J2000.0 * pmain is proper motion in ra in seconds of time per Julian century. * pmdin is proper motion in dec in seconds of arc per Julian century. * pin is parallax in arc seconds. (0.0d0 if unknown) * vin is radial velocity in km/sec. (0.0d0 if unknown) * ieflg is flag allowing restore of E-terms of aberration. Usually ieflg * should = +1 (to restore the E-terms to the B1950 position). * ieflg =-1 do not replace E-terms (there none). * ieflg = anything but -1 indicates E-terms are to be present * and are to be replaced. * eqxbou is ignored (assumed to be 1950.0d0); * is output equinox (besselian): * Returned values: * raout is right ascension (decimal degrees) at equinox,epoch B1950. * decout is declination (decimal degrees) at equinox,epoch B1950. * pmaout is proper motion in ra in seconds of time per tropical century. * pmdout is proper motion in dec in seconds of arc per tropical century. * * **************************************************************************** * */ double ra, dec, tobsb=1950.0; double rat, dect, delt, dela, pmat, pmdt, rar, decr; double eqx1 = 2000.0, eqx2 = 1950.0, dtor; double corra, corrd, corrpa, corrpd; double jde, tobsj, work; dtor = atan(1.0)/45.0; ra = rain; dec = decin; jde = ((tobsb - 1950.0) * 365.2421988) + 2433282.4235; tobsj = 2000.0 + ((jde - 2451545.0)/365.25); fk5prp( eqx1, ra, dec, pmain, pmdin, pin, vin, tobsj, &rat, &dect, &pmat, &pmdt); /* * re: proper motions: remove adjustment for precession constant; * remove equinox corr. for proper motion in ra; * convert from units per Julian centry to units per tropical century: */ rar = dtor*rat; decr = dtor*dect; if(fabs(dect) > 89.9999) work = 0.0; else work = 0.0291*sin(rar)*tan(decr); pmat = pmat + 0.06912 + work - 0.0850; *pmaout = pmat / 1.00002136; pmdt = pmdt + 0.436 * cos(rar); *pmdout = pmdt / 1.00002136; /* * remove the equinox correction (use tobsb not tobsj): * */ delt = (tobsb - 1950.0) * 0.01; dela = ((0.035 + 0.085*delt) * 15.0) / 3600.0; rat = rat - dela; if(rat >= 360.0) rat = rat - 360.0; else if(rat < 0.0) rat = rat + 360.0; /* * Add back E-terms if necessary: */ if(ieflg != -1) jaddet(tobsj,&rat,&dect); if(japply != 0) { /* remove the fk5-fk4 systematic corrections: */ junfkc(rat,dect,0.0,tobsb,&corra,&corrd,&corrpa,&corrpd); rat = rat - corra; dect = dect - corrd; *pmaout = *pmaout - corrpa; *pmdout = *pmdout - corrpd; jclpos(&rat,&dect); } *raout = rat; *decout = dect; return 0; } itere(ra,dec,edela,edeld) double ra, dec, *edela, *edeld; { /* for adding E-term back (note: w/ supp. formulas, edela,edeld are added to * ra and dec to remove the E-term; therefore subtract here. */ int i,iend1; double rwork,dwork; rwork = ra; dwork = dec; iend1 = 3; for (i=0; i<iend1;i++) { gtetrm(rwork,dwork,edela,edeld); if (i == 2) return 0; rwork = ra - *edela; dwork = dec - *edeld; jclpos(&rwork,&dwork); } return 0; } gtetrm(ra,dec,dela,deld) double ra, dec, *dela, *deld; { /* * from Suppl. to Astron. Alman. 1984 (also 1961 supp. page 144) * see also, Standish, A&A 115, 20-22 (1982) * * compute E-terms to be removed for object at ra and dec. * all args. double precision and in decimal degrees) * * Since the E-terms (terms of elliptic aberration) change so slowly * (Smart,Textbook on Spherical Astronomy, Sixth Ed. Section 108,p186) * these values do not require t as input and will be valid in the * 1950 to 2000 time span we are dealing with. * * The 1961 supp called these equations an approximation and stated that * small errors in this procedure are usually negligible. However, they * did not explain what lead up to the procedure: "The form of the equations * of condition and their solution are not discussed here." * */ static int nthrue=0; static double e1, e2, e3, e4, dtor; double dcosd, alplus; if(nthrue == 0) { dtor = atan(1.0) / 45.0; /* note: e1 = (0.0227 * 15.0) / 3600.0 = 0.341/3600 = e3 */ e2 = 11.25 * 15.0; e3 = 0.341 / 3600.0; e4 = 0.029 / 3600.0; e1 = e3; nthrue = 1; } alplus = ra + e2; if(alplus >= 360.0) alplus = alplus - 360.0; alplus = alplus * dtor; dcosd = cos(dtor * dec); if(fabs(dec) >= 90.0 || fabs(dcosd) < 1.0e0-27) { *dela = 0.0; *deld = 0.0; } else *dela = (e1 * sin(alplus)) / dcosd; *deld = (e3 * cos(alplus) * sin(dec*dtor)) + (e4 * dcosd); return 0; } gtecle(epoch, lambda, beta, dela, deld) double epoch, lambda, beta, *dela, *deld; { /* * * compute E-terms at epoch for ecliptic lambda, beta input (returned in dela, * deld (degrees). * epoch in years (e.g. 1950.000), lambda,beta,,dela,deld in decimal degrees. * All arguments double precision. * * E-term formulas from ASTRONOMICAL ALGORITHMS by Jean Meeus (1991) ch.22 * Note: equations as presented are for computing E-terms from position * that does not contain E-terms. To get better answer (when * splitting hairs), iterate to get best E-term (for position that * has E-terms) to be removed. Subroutine iterec may be called to * to do the iteration. * Note 2: these formulas for E-terms, as function of ecliptic lon and lat, * also appear in Spherical Astronomy by R.Green (1985),page 192; * and in Textbook on Spherical Astronomy, Sixth Ed.,by Smart (1977), * page 186. * * To remove E-terms, subtract dela & deld from lamba & beta, respectively, * in the calling program. * To add back E-terms, add dela & deld to lambda & beta, respectively, in * the calling program. * * */ static int nthrue = 0; static double dtor, kappa, lepoch=-1.0, e, pirad; double t, t2, pi, lrad, brad; if(nthrue == 0) { dtor = atan(1.0) / 45.0; /* constant of aberration, kappa = 20.49552" "new" ("old" was 20.496) */ kappa = 0.0056932; nthrue = 1; } *dela = 0.0; *deld = 0.0; if(epoch != lepoch) { t = (epoch - 2000.0) * 0.01; t2 = t*t; lepoch = epoch; /* * e = eccentricity of the Earth's orbit * pi= longitude of the perihelion of this orbit */ e = 0.016708617 - 0.000042037*t - 0.0000001236*t2; pi= 102.93735 + 0.71953*t + 0.00046*t2; pirad = dtor * pi; } if(fabs(beta) > 89.999) return 0; lrad = dtor*lambda; brad = dtor*beta; *dela = e * kappa * cos(pirad-lrad) / cos(brad); *deld = e * kappa * sin(pirad-lrad) * sin(brad); return 0; } iterec(tobsj,lambda,beta,edela,edeld) double tobsj,lambda,beta,*edela,*edeld; { int i, iend1 = 3; double lwork,bwork; lwork = lambda; bwork = beta; for (i=0; i<iend1; i++) { gtecle(tobsj,lwork,bwork,edela,edeld); lwork = lambda - *edela; bwork = beta - *edeld; jclpos(&lwork,&bwork); } return 0; } jrmvet(tobsj,rat,dect) double tobsj,*rat,*dect; { /*c Remove E-terms: * 31jul92 update to use equecx and ecleqx instead of equec2 and ecleq2. */ double edela,edeld; double lambda, beta, pole=89.999; if(fabs(*dect) < pole) { gtetrm( *rat, *dect, &edela, &edeld); *rat = *rat + edela; *dect = *dect + edeld; jclpos(rat, dect); } else { /* note: using "Julian system" (iaus=2 for equecx and ecleqx) here - * makes no. dif in resulting E-terms and simplifies argument * list required for jrmvet. */ equecx(2,tobsj,*rat,*dect,&lambda,&beta); iterec(tobsj,lambda,beta,&edela,&edeld); lambda = lambda - edela; beta = beta - edeld; jclpos(&lambda, &beta); ecleqx(2,tobsj,lambda,beta,rat,dect); } return 0; } jaddet(tobsj,rat,dect) double tobsj,*rat,*dect; { /* Add back E-terms: * 31jul92 update to use equecx and ecleqx instead of equec2 and ecleq2. */ double edela, edeld, lambda, beta, pole = 89.999; if(fabs(*dect) < pole) { itere( *rat, *dect, &edela, &edeld); *rat = *rat - edela; *dect = *dect - edeld; jclpos(rat,dect); } else { equecx(2,tobsj, *rat, *dect, &lambda, &beta); gtecle(tobsj, lambda, beta, &edela, &edeld); lambda = lambda + edela; beta = beta + edeld; jclpos(&lambda, &beta); ecleqx(2,tobsj, lambda, beta, rat, dect); } return 0; } jclpos(rat,dect) double *rat, *dect; { /* to put ra into 0 to 360 and dec into -90 to +90 ranges.*/ if(*rat > 360.0) *rat = *rat - 360.0; else if(*rat < 0.0) *rat = *rat + 360.0; if(fabs(*dect) > 90.0) { *rat = *rat + 180.0; if(*rat >= 360.0) *rat = *rat - 360.0; if(*dect > 0.0) *dect = 180.0 - *dect; else *dect = -(180.0 + *dect); } return 0; }
the_stack_data/218893355.c
int main(int argc, char** argv) { return 1; }
the_stack_data/987297.c
/** * @brief This function handles NMI exception. * @param None * @retval None */ void NMI_Handler(void) { } /** * @brief This function handles Hard Fault exception. * @param None * @retval None */ void HardFault_Handler(void) { while (1); } /** * @brief This function handles SVCall exception. * @param None * @retval None */ void SVC_Handler(void) { } /** * @brief This function handles PendSVC exception. * @param None * @retval None */ void PendSV_Handler(void) { }
the_stack_data/200143923.c
#include <stdio.h> int function(int arg1, char *arg2, char arg3, double arg4) { printf("-----:\n"); printf("arg1: %d\n", arg1); printf("arg2: %s\n", arg2); printf("arg3: %c\n", arg3); printf("arg4: %9.8g\n\n", arg4); return 0; } typedef char byte; byte ary[13]; struct foo { byte data[24]; } fee; typedef int (*foo_fun)(struct foo); struct bar { int arg1; char *arg2; char arg3; double arg4; } bee; typedef int (*bar_fun)(struct bar); int fun2(struct foo f) { printf("arg1: %d\n", f.data[0]); return 0; } inline void poke_int(void *address, int *offset, int value) { *(int *)((byte *)address + *offset) = value; *offset += sizeof(int); } inline void poke_ptr(void *address, int *offset, void *value) { *(byte **)((byte *)address + *offset) = value; *offset += sizeof(void *); } inline void poke_char(void *address, int *offset, char value) { *(char *)((byte *)address + *offset) = value; *offset += sizeof(int); } inline void poke_double(void *address, int *offset, double value) { *(double *)((byte *)address + *offset) = value; *offset += sizeof(double); } int main(int argc, char **argv) { printf("sizeof ary=%d\n", sizeof(ary)); printf("sizeof foo=%d\n", sizeof(struct foo)); //fun2(fee); //(int *)(fee.data[0]) = 55; //(char **)(fee.data[0]) = "hello"; //(char **)(fee.data[sizeof(int)]) = "hello"; //(char *)(fee.data[sizeof(int) + sizeof(char *)]) = 'k'; //(double *)(fee.data[sizeof(int) + sizeof(char *) + sizeof(double)]) = 178.213; //((foo_fun)function)(fee); bee.arg1 = 55; bee.arg2 = "hello"; bee.arg3 = 'k'; bee.arg4 = 178.213; ((bar_fun)function)(bee); { int offset = 0; poke_int(&fee, &offset, 66); poke_ptr(&fee, &offset, "goodbye"); poke_char(&fee, &offset, 'j'); poke_double(&fee, &offset, 91.3171); } ((foo_fun)function)(fee); }
the_stack_data/176705279.c
#include<stdio.h> #include<stdlib.h> struct node { int data; struct node *left; struct node *right; }; struct node *ROOT=NULL; int min; struct node *build_tree(struct node *t,int data) { if(t!=NULL) { if(data< t->data) t->left=build_tree(t->left,data); if(data> t->data) t->right=build_tree(t->right,data); } else { t=malloc(sizeof(struct node)); t->data=data; t->left=NULL; t->right=NULL; } return t; } struct node *deleted(int x,struct node *root) { if(root!=NULL) { if(x< root->data) root->left=deleted(x,root->left); else if(x>root->data) root->right=deleted(x,root->right); else { struct node *t=NULL; if(root->left==NULL && root->right==NULL) { free(root); root=NULL; } else if(root->left==NULL) { t=root->right; free(root); root=t; } else if(root->right==NULL) { t=root->left; free(root); root=t; } else { t=root->right; while(t->left!=NULL) t=t->left; root->data=t->data; root->right=deleted(t->data,root->right); } } } return root; } void inorder(struct node *t) { if(t!=NULL) { inorder(t->left); printf("%d ",t->data); inorder(t->right); } } void main() { int data,n,i,choice,x; while(1) { printf("\n1.Insert\n2.Delete\n3.Exit\n"); printf("Choice:"); scanf("%d",&choice); switch(choice) { case 1: printf("Enter the number of nodes: "); scanf("%d",&n); for(i=0;i<n;i++) { printf("Enter the element at [%d]: ",i); scanf("%d",&data); ROOT=build_tree(ROOT,data); } printf("\nINORDER : "); inorder(ROOT); break; case 2: printf("Enter the element to be deleted: "); scanf("%d",&x); ROOT=deleted(x,ROOT); printf("\nINORDER : "); inorder(ROOT); break; case 3: return; } } }
the_stack_data/590745.c
#include<stdio.h> #define SIZE 10 #undef SIZE #define SIZE 20 int main(void) { printf("%d",SIZE); }
the_stack_data/518841.c
// ftell_ex.c : ftell() example // ------------------------------------------------------------- // This example searches in a file, whose name is the second command-line // argument, for a string, which the user can specify in the first // command-line argument. #include <stdio.h> // long ftell( FILE *fp ); #include <stdlib.h> #include <string.h> #define MAX_LINE 256 int main( int argc, char *argv[]) { FILE *fp; long lOffset = 0L; char sLine[MAX_LINE] = ""; int lineno = 0; if ( argc != 3 ) fprintf( stderr, "Usage: program search_string file_name\n"), exit(1); if ((fp = fopen(argv[2], "r")) == NULL) { fprintf(stderr, "Unable to open file %s\n", argv[2]); exit(-1); } do { lOffset = ftell(fp); // Bookmark the beginning of // the line we're about to read. if ( -1L == lOffset ) fprintf(stderr, "Unable to obtain offset in %s\n", argv[2]); else lineno++; if ( !fgets(sLine, MAX_LINE, fp)) // Read next line from file. break; } while ( strstr( sLine, argv[1]) == NULL); // Test for argument // in sLine. /* Dropped out of loop: Found search keyword or EOF */ if ( feof(fp) || ferror(fp) ) { fprintf(stderr, "Unable to find \"%s\" in %s\n", argv[1], argv[2]); rewind(fp); } else { printf( "%s (%d): %s\n", argv[2], lineno, sLine); fseek( fp, lOffset, 0); // Set file pointer at beginning of // the line containing the keyword } return 0; }
the_stack_data/103264385.c
#include <stdio.h> #include <stdlib.h> char N(int i) { switch (i) { case 0: return 'n'; case 1: return 'i'; case 2: return 'z'; case 3: return 's'; default: printf("Error: index overflow in N().\n"); exit(-1); } } char O(int i) { switch (i) { case 0: return 'o'; case 1: return 'i'; default: printf("Error: index overflow in O().\n"); exit(-1); } } char E(int i) { switch (i) { case 0: return 'e'; case 1: return 'i'; case 2: return 'w'; case 3: return 'm'; default: printf("Error: index overflow in E().\n"); exit(-1); } } char L(int i) { switch (i) { case 0: return 'l'; case 1: return 'i'; case 2: return 'c'; case 3: return 'v'; case 4: return 'j'; default: printf("Error: index overflow in L().\n"); exit(-1); } } void cycle(FILE *f, char n, char o, char e, char l) { fprintf(f, "%c%c%c%c\n", n, o, e, l); fprintf(f, "%c%c%c%c\n", n, o, l, e); fprintf(f, "%c%c%c%c\n", n, e, o, l); fprintf(f, "%c%c%c%c\n", n, e, l, o); fprintf(f, "%c%c%c%c\n", n, l, o, e); fprintf(f, "%c%c%c%c\n", n, l, e, o); fprintf(f, "%c%c%c%c\n", o, n, e, l); fprintf(f, "%c%c%c%c\n", o, n, l, e); fprintf(f, "%c%c%c%c\n", o, e, n, l); fprintf(f, "%c%c%c%c\n", o, e, l, n); fprintf(f, "%c%c%c%c\n", o, l, n, e); fprintf(f, "%c%c%c%c\n", o, l, e, n); fprintf(f, "%c%c%c%c\n", e, n, o, l); fprintf(f, "%c%c%c%c\n", e, n, l, o); fprintf(f, "%c%c%c%c\n", e, o, n, l); fprintf(f, "%c%c%c%c\n", e, o, l, n); fprintf(f, "%c%c%c%c\n", e, l, n, o); fprintf(f, "%c%c%c%c\n", e, l, o, n); fprintf(f, "%c%c%c%c\n", l, n, o, e); fprintf(f, "%c%c%c%c\n", l, n, e, o); fprintf(f, "%c%c%c%c\n", l, o, n, e); fprintf(f, "%c%c%c%c\n", l, o, e, n); fprintf(f, "%c%c%c%c\n", l, e, n, o); fprintf(f, "%c%c%c%c\n", l, e, o, n); } int main(int argc, char *argv[]) { int nI, oI, eI, lI; FILE *f = fopen("all-noel-combos.txt", "w"); for (nI = 0 ; nI < 4 ; nI++) for (oI = 0 ; oI < 2 ; oI++) for (eI = 0 ; eI < 4 ; eI++) for (lI = 0 ; lI < 5 ; lI++) cycle(f, N(nI), O(oI), E(eI), L(lI)); printf("Output written to all-noel-combos.txt.\n"); fclose (f); return 0; }
the_stack_data/18650.c
/* Name: p7q5.c Desc: Calculate parking fee */ #include <stdio.h> #include <string.h> #include <stdlib.h> void displayVehicleRate(char vehicleType); char getVehicleType(void); int calcHoursParked(int inHr, int inMin, int outHr, int outMin); double parkingCharge(char vehicleType, int hrsParked); int main(void) { //variables char vehicleType; double hours; int inHr, inMin, outHr, outMin; //get vehicle type vehicleType = getVehicleType(); //get parking hours printf("Time entered car park (hh mm)?: "); scanf("%d %d", &inHr, &inMin); rewind(stdin); printf("Time exited car park (hh mm): "); scanf("%d %d", &outHr, &outMin); rewind(stdin); //print headings printf("========================================================\n" " Parking Ticket\n" ); //display rate displayVehicleRate(vehicleType); //display hours parked hours = calcHoursParked(inHr, inMin, outHr, outMin); if (hours == -1) { printf("\n" "Error, please see the management.\n"); exit(-1); } printf("Hours parked : %.2f\n", hours); //get total payment printf("Please pay this amount ------> RM %.2f\n", parkingCharge(vehicleType, hours)); //print footer printf("Thank You & Have a Nice Day !\n" "========================================================\n"); } void displayVehicleRate(char vehicleType) { //variables char type[10]; double rate; switch (vehicleType) { case 'c': strcpy(type, "CAR"); rate = 2.00; break; case 'b': strcpy(type, "BUS"); rate = 3.00; break; case 't': strcpy(type, "TRUCK"); rate = 4.00; break; default: printf("Invalid vehicle type.\n"); rate = 0.00; } printf("Vehicle Type : %s => RM %.2f per hour (or part thereof)\n", type, rate); } char getVehicleType(void) { char type; do { printf("Vehicle type : c(ar), b(us), t(ruck)? "); scanf("%c", &type); rewind(stdin); } while (type != 'c' && type != 'b' && type != 't'); return type; } int calcHoursParked(int inHr, int inMin, int outHr, int outMin) { //check for validity if (inHr < 7 || inHr > 24) { return -1; } else if (outHr < 7 || outHr > 24) { return -1; } else if (outHr < inHr) { return -1; } else if (outHr >= 24 && outMin > 0) { return -1; } //variables int hours, minutes; //obtain hours parked (without fractions) hours = outHr - inHr; //obtain hours parked (for fractions) minutes = outMin - inMin; //if its positive then count as one hour if (minutes > 0) { hours++; } //otherwise dont count //if total parked hours exceed 17 hours ( outside of 7am-12pm ), report error if(hours > 17) { return -1; } return hours; } double parkingCharge(char vehicleType, int hrsParked) { //variables char rate; double charge; //check vehicleType switch (vehicleType) { case 'c': rate = 2.00; break; case 'b': rate = 3.00; break; case 't': rate = 4.00; break; } //determine charge //multiply by hours parked charge = hrsParked * rate; //return parking charge return charge; }
the_stack_data/90954.c
#include <stdio.h> int main() { int n; printf("enter no of stars\n"); scanf("%d",&n); int i ,j; for(i=0;i<n;i++) { if(i==0||i==n-1) { for(j=0;j<n;j++) printf("* "); } else { for(j=0;j<=n;j++) { if(j==0) printf("*"); else if(j==n) printf(" *"); else if(j<n-1) printf(" $"); } } printf("\n"); } return 0; }
the_stack_data/411834.c
#include <stdio.h> #include <stdlib.h> int main() { int *p1,c; c = 4; printf("p adresi X: %p\n", &p1); //kendi adresini // p1 = &c; printf("adresi: %p\n", &c); printf("p adresi: %p\n", p1); printf("p adresi X: %p\n", &p1); //kendi adresini }
the_stack_data/36075722.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strchr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: nhakkaou <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/10/05 15:08:54 by nhakkaou #+# #+# */ /* Updated: 2018/10/07 12:13:38 by nhakkaou ### ########.fr */ /* */ /* ************************************************************************** */ char *ft_strchr(const char *s, int c) { int i; char find; i = 0; find = c; while (s[i] != '\0') { if (s[i] == find) return ((char *)s + i); i++; } if (s[i] == find) return ((char *)s + i); return (0); }
the_stack_data/40764256.c
/* * Copyright (C) Andreas Neuper, Sep 1998. * * Licensed under GPLv2, see file LICENSE in this source tree. */ #if ENABLE_FEATURE_SGI_LABEL #define SGI_DEBUG 0 #define SGI_VOLHDR 0x00 /* 1 and 2 were used for drive types no longer supported by SGI */ #define SGI_SWAP 0x03 /* 4 and 5 were for filesystem types SGI haven't ever supported on MIPS CPUs */ #define SGI_VOLUME 0x06 #define SGI_EFS 0x07 #define SGI_LVOL 0x08 #define SGI_RLVOL 0x09 #define SGI_XFS 0x0a #define SGI_XFSLOG 0x0b #define SGI_XLV 0x0c #define SGI_XVM 0x0d #define SGI_ENTIRE_DISK SGI_VOLUME struct device_parameter { /* 48 bytes */ unsigned char skew; unsigned char gap1; unsigned char gap2; unsigned char sparecyl; unsigned short pcylcount; unsigned short head_vol0; unsigned short ntrks; /* tracks in cyl 0 or vol 0 */ unsigned char cmd_tag_queue_depth; unsigned char unused0; unsigned short unused1; unsigned short nsect; /* sectors/tracks in cyl 0 or vol 0 */ unsigned short bytes; unsigned short ilfact; unsigned int flags; /* controller flags */ unsigned int datarate; unsigned int retries_on_error; unsigned int ms_per_word; unsigned short xylogics_gap1; unsigned short xylogics_syncdelay; unsigned short xylogics_readdelay; unsigned short xylogics_gap2; unsigned short xylogics_readgate; unsigned short xylogics_writecont; }; /* * controller flags */ #define SECTOR_SLIP 0x01 #define SECTOR_FWD 0x02 #define TRACK_FWD 0x04 #define TRACK_MULTIVOL 0x08 #define IGNORE_ERRORS 0x10 #define RESEEK 0x20 #define ENABLE_CMDTAGQ 0x40 typedef struct { unsigned int magic; /* expect SGI_LABEL_MAGIC */ unsigned short boot_part; /* active boot partition */ unsigned short swap_part; /* active swap partition */ unsigned char boot_file[16]; /* name of the bootfile */ struct device_parameter devparam; /* 1 * 48 bytes */ struct volume_directory { /* 15 * 16 bytes */ unsigned char vol_file_name[8]; /* a character array */ unsigned int vol_file_start; /* number of logical block */ unsigned int vol_file_size; /* number of bytes */ } directory[15]; struct sgi_partinfo { /* 16 * 12 bytes */ unsigned int num_sectors; /* number of blocks */ unsigned int start_sector; /* must be cylinder aligned */ unsigned int id; } partitions[16]; unsigned int csum; unsigned int fillbytes; } sgi_partition; typedef struct { unsigned int magic; /* looks like a magic number */ unsigned int a2; unsigned int a3; unsigned int a4; unsigned int b1; unsigned short b2; unsigned short b3; unsigned int c[16]; unsigned short d[3]; unsigned char scsi_string[50]; unsigned char serial[137]; unsigned short check1816; unsigned char installer[225]; } sgiinfo; #define SGI_LABEL_MAGIC 0x0be5a941 #define SGI_LABEL_MAGIC_SWAPPED 0x41a9e50b #define SGI_INFO_MAGIC 0x00072959 #define SGI_INFO_MAGIC_SWAPPED 0x59290700 #define SGI_SSWAP16(x) (sgi_other_endian ? fdisk_swap16(x) : (uint16_t)(x)) #define SGI_SSWAP32(x) (sgi_other_endian ? fdisk_swap32(x) : (uint32_t)(x)) #define sgilabel ((sgi_partition *)MBRbuffer) #define sgiparam (sgilabel->devparam) /* * * fdisksgilabel.c * * Copyright (C) Andreas Neuper, Sep 1998. * This file may be modified and redistributed under * the terms of the GNU Public License. * * Sat Mar 20 EST 1999 Arnaldo Carvalho de Melo <[email protected]> * Internationalization */ static smallint sgi_other_endian; /* bool */ static smallint sgi_volumes = 1; /* max 15 */ /* * only dealing with free blocks here */ typedef struct { unsigned int first; unsigned int last; } freeblocks; static freeblocks freelist[17]; /* 16 partitions can produce 17 vacant slots */ static void setfreelist(int i, unsigned int f, unsigned int l) { freelist[i].first = f; freelist[i].last = l; } static void add2freelist(unsigned int f, unsigned int l) { int i; for (i = 0; i < 17; i++) if (freelist[i].last == 0) break; setfreelist(i, f, l); } static void clearfreelist(void) { int i; for (i = 0; i < 17; i++) setfreelist(i, 0, 0); } static unsigned int isinfreelist(unsigned int b) { int i; for (i = 0; i < 17; i++) if (freelist[i].first <= b && freelist[i].last >= b) return freelist[i].last; return 0; } /* return last vacant block of this stride (never 0). */ /* the '>=' is not quite correct, but simplifies the code */ /* * end of free blocks section */ static const char *const sgi_sys_types[] = { /* SGI_VOLHDR */ "\x00" "SGI volhdr" , /* 0x01 */ "\x01" "SGI trkrepl" , /* 0x02 */ "\x02" "SGI secrepl" , /* SGI_SWAP */ "\x03" "SGI raw" , /* 0x04 */ "\x04" "SGI bsd" , /* 0x05 */ "\x05" "SGI sysv" , /* SGI_ENTIRE_DISK */ "\x06" "SGI volume" , /* SGI_EFS */ "\x07" "SGI efs" , /* 0x08 */ "\x08" "SGI lvol" , /* 0x09 */ "\x09" "SGI rlvol" , /* SGI_XFS */ "\x0a" "SGI xfs" , /* SGI_XFSLOG */ "\x0b" "SGI xfslog" , /* SGI_XLV */ "\x0c" "SGI xlv" , /* SGI_XVM */ "\x0d" "SGI xvm" , /* LINUX_SWAP */ "\x82" "Linux swap" , /* LINUX_NATIVE */ "\x83" "Linux native", /* LINUX_LVM */ "\x8d" "Linux LVM" , /* LINUX_RAID */ "\xfd" "Linux RAID" , NULL }; static int sgi_get_nsect(void) { return SGI_SSWAP16(sgilabel->devparam.nsect); } static int sgi_get_ntrks(void) { return SGI_SSWAP16(sgilabel->devparam.ntrks); } static unsigned int two_s_complement_32bit_sum(unsigned int* base, int size /* in bytes */) { int i = 0; unsigned int sum = 0; size /= sizeof(unsigned int); for (i = 0; i < size; i++) sum -= SGI_SSWAP32(base[i]); return sum; } void BUG_bad_sgi_partition_size(void); static int check_sgi_label(void) { if (sizeof(sgi_partition) > 512) { /* According to MIPS Computer Systems, Inc the label * must not contain more than 512 bytes */ BUG_bad_sgi_partition_size(); } if (sgilabel->magic != SGI_LABEL_MAGIC && sgilabel->magic != SGI_LABEL_MAGIC_SWAPPED ) { current_label_type = LABEL_DOS; return 0; } sgi_other_endian = (sgilabel->magic == SGI_LABEL_MAGIC_SWAPPED); /* * test for correct checksum */ if (two_s_complement_32bit_sum((unsigned int*)sgilabel, sizeof(*sgilabel))) { printf("Detected sgi disklabel with wrong checksum\n"); } update_units(); current_label_type = LABEL_SGI; g_partitions = 16; sgi_volumes = 15; return 1; } static unsigned int sgi_get_start_sector(int i) { return SGI_SSWAP32(sgilabel->partitions[i].start_sector); } static unsigned int sgi_get_num_sectors(int i) { return SGI_SSWAP32(sgilabel->partitions[i].num_sectors); } static int sgi_get_sysid(int i) { return SGI_SSWAP32(sgilabel->partitions[i].id); } static int sgi_get_bootpartition(void) { return SGI_SSWAP16(sgilabel->boot_part); } static int sgi_get_swappartition(void) { return SGI_SSWAP16(sgilabel->swap_part); } static void sgi_list_table(int xtra) { int i, w, wd; int kpi = 0; /* kernel partition ID */ if (xtra) { printf("\nDisk %s (SGI disk label): %u heads, %u sectors\n" "%u cylinders, %u physical cylinders\n" "%u extra sects/cyl, interleave %u:1\n" "%s\n" "Units = %s of %u * 512 bytes\n\n", disk_device, g_heads, g_sectors, g_cylinders, SGI_SSWAP16(sgiparam.pcylcount), SGI_SSWAP16(sgiparam.sparecyl), SGI_SSWAP16(sgiparam.ilfact), (char *)sgilabel, str_units(PLURAL), units_per_sector); } else { printf("\nDisk %s (SGI disk label): " "%u heads, %u sectors, %u cylinders\n" "Units = %s of %u * 512 bytes\n\n", disk_device, g_heads, g_sectors, g_cylinders, str_units(PLURAL), units_per_sector ); } w = strlen(disk_device); wd = sizeof("Device") - 1; if (w < wd) w = wd; printf("----- partitions -----\n" "Pt# %*s Info Start End Sectors Id System\n", w + 2, "Device"); for (i = 0; i < g_partitions; i++) { if (sgi_get_num_sectors(i) || SGI_DEBUG) { uint32_t start = sgi_get_start_sector(i); uint32_t len = sgi_get_num_sectors(i); kpi++; /* only count nonempty partitions */ printf( "%2u: %s %4s %9lu %9lu %9lu %2x %s\n", /* fdisk part number */ i+1, /* device */ partname(disk_device, kpi, w+3), /* flags */ (sgi_get_swappartition() == i) ? "swap" : /* flags */ (sgi_get_bootpartition() == i) ? "boot" : " ", /* start */ (long) scround(start), /* end */ (long) scround(start+len)-1, /* no odd flag on end */(long) len, /* type id */ sgi_get_sysid(i), /* type name */ partition_type(sgi_get_sysid(i))); } } printf("----- Bootinfo -----\nBootfile: %s\n" "----- Directory Entries -----\n", sgilabel->boot_file); for (i = 0; i < sgi_volumes; i++) { if (sgilabel->directory[i].vol_file_size) { uint32_t start = SGI_SSWAP32(sgilabel->directory[i].vol_file_start); uint32_t len = SGI_SSWAP32(sgilabel->directory[i].vol_file_size); unsigned char *name = sgilabel->directory[i].vol_file_name; printf("%2u: %-10s sector%5u size%8u\n", i, (char*)name, (unsigned int) start, (unsigned int) len); } } } static void sgi_set_bootpartition(int i) { sgilabel->boot_part = SGI_SSWAP16(((short)i)); } static unsigned int sgi_get_lastblock(void) { return g_heads * g_sectors * g_cylinders; } static void sgi_set_swappartition(int i) { sgilabel->swap_part = SGI_SSWAP16(((short)i)); } static int sgi_check_bootfile(const char* aFile) { if (strlen(aFile) < 3) /* "/a\n" is minimum */ { printf("\nInvalid Bootfile!\n" "\tThe bootfile must be an absolute non-zero pathname,\n" "\te.g. \"/unix\" or \"/unix.save\".\n"); return 0; } if (strlen(aFile) > 16) { printf("\nName of Bootfile too long (>16 bytes)\n"); return 0; } if (aFile[0] != '/') { printf("\nBootfile must have a fully qualified pathname\n"); return 0; } if (strncmp(aFile, (char*)sgilabel->boot_file, 16)) { printf("\nBe aware, that the bootfile is not checked for existence.\n" "\tSGI's default is \"/unix\" and for backup \"/unix.save\".\n"); /* filename is correct and did change */ return 1; } return 0; /* filename did not change */ } static const char * sgi_get_bootfile(void) { return (char*)sgilabel->boot_file; } static void sgi_set_bootfile(const char* aFile) { int i = 0; if (sgi_check_bootfile(aFile)) { while (i < 16) { if ((aFile[i] != '\n') /* in principle caught again by next line */ && (strlen(aFile) > i)) sgilabel->boot_file[i] = aFile[i]; else sgilabel->boot_file[i] = 0; i++; } printf("\n\tBootfile is changed to \"%s\"\n", sgilabel->boot_file); } } static void create_sgiinfo(void) { /* I keep SGI's habit to write the sgilabel to the second block */ sgilabel->directory[0].vol_file_start = SGI_SSWAP32(2); sgilabel->directory[0].vol_file_size = SGI_SSWAP32(sizeof(sgiinfo)); strncpy((char*)sgilabel->directory[0].vol_file_name, "sgilabel", 8); } static sgiinfo *fill_sgiinfo(void); static void sgi_write_table(void) { sgilabel->csum = 0; sgilabel->csum = SGI_SSWAP32(two_s_complement_32bit_sum( (unsigned int*)sgilabel, sizeof(*sgilabel))); assert(two_s_complement_32bit_sum( (unsigned int*)sgilabel, sizeof(*sgilabel)) == 0); write_sector(0, sgilabel); if (!strncmp((char*)sgilabel->directory[0].vol_file_name, "sgilabel", 8)) { /* * keep this habit of first writing the "sgilabel". * I never tested whether it works without (AN 981002). */ sgiinfo *info = fill_sgiinfo(); int infostartblock = SGI_SSWAP32(sgilabel->directory[0].vol_file_start); write_sector(infostartblock, info); free(info); } } static int compare_start(int *x, int *y) { /* * sort according to start sectors * and prefers largest partition: * entry zero is entire disk entry */ unsigned int i = *x; unsigned int j = *y; unsigned int a = sgi_get_start_sector(i); unsigned int b = sgi_get_start_sector(j); unsigned int c = sgi_get_num_sectors(i); unsigned int d = sgi_get_num_sectors(j); if (a == b) return (d > c) ? 1 : (d == c) ? 0 : -1; return (a > b) ? 1 : -1; } static int verify_sgi(int verbose) { int Index[16]; /* list of valid partitions */ int sortcount = 0; /* number of used partitions, i.e. non-zero lengths */ int entire = 0, i = 0; unsigned int start = 0; long long gap = 0; /* count unused blocks */ unsigned int lastblock = sgi_get_lastblock(); clearfreelist(); for (i = 0; i < 16; i++) { if (sgi_get_num_sectors(i) != 0) { Index[sortcount++] = i; if (sgi_get_sysid(i) == SGI_ENTIRE_DISK) { if (entire++ == 1) { if (verbose) printf("More than one entire disk entry present\n"); } } } } if (sortcount == 0) { if (verbose) printf("No partitions defined\n"); return (lastblock > 0) ? 1 : (lastblock == 0) ? 0 : -1; } qsort(Index, sortcount, sizeof(Index[0]), (void*)compare_start); if (sgi_get_sysid(Index[0]) == SGI_ENTIRE_DISK) { if ((Index[0] != 10) && verbose) printf("IRIX likes when Partition 11 covers the entire disk\n"); if ((sgi_get_start_sector(Index[0]) != 0) && verbose) printf("The entire disk partition should start " "at block 0,\n" "not at diskblock %u\n", sgi_get_start_sector(Index[0])); if (SGI_DEBUG) /* I do not understand how some disks fulfil it */ if ((sgi_get_num_sectors(Index[0]) != lastblock) && verbose) printf("The entire disk partition is only %u diskblock large,\n" "but the disk is %u diskblocks long\n", sgi_get_num_sectors(Index[0]), lastblock); lastblock = sgi_get_num_sectors(Index[0]); } else { if (verbose) printf("One Partition (#11) should cover the entire disk\n"); if (SGI_DEBUG > 2) printf("sysid=%u\tpartition=%u\n", sgi_get_sysid(Index[0]), Index[0]+1); } for (i = 1, start = 0; i < sortcount; i++) { int cylsize = sgi_get_nsect() * sgi_get_ntrks(); if ((sgi_get_start_sector(Index[i]) % cylsize) != 0) { if (SGI_DEBUG) /* I do not understand how some disks fulfil it */ if (verbose) printf("Partition %u does not start on cylinder boundary\n", Index[i]+1); } if (sgi_get_num_sectors(Index[i]) % cylsize != 0) { if (SGI_DEBUG) /* I do not understand how some disks fulfil it */ if (verbose) printf("Partition %u does not end on cylinder boundary\n", Index[i]+1); } /* We cannot handle several "entire disk" entries. */ if (sgi_get_sysid(Index[i]) == SGI_ENTIRE_DISK) continue; if (start > sgi_get_start_sector(Index[i])) { if (verbose) printf("Partitions %u and %u overlap by %u sectors\n", Index[i-1]+1, Index[i]+1, start - sgi_get_start_sector(Index[i])); if (gap > 0) gap = -gap; if (gap == 0) gap = -1; } if (start < sgi_get_start_sector(Index[i])) { if (verbose) printf("Unused gap of %u sectors - sectors %u-%u\n", sgi_get_start_sector(Index[i]) - start, start, sgi_get_start_sector(Index[i])-1); gap += sgi_get_start_sector(Index[i]) - start; add2freelist(start, sgi_get_start_sector(Index[i])); } start = sgi_get_start_sector(Index[i]) + sgi_get_num_sectors(Index[i]); if (SGI_DEBUG > 1) { if (verbose) printf("%2u:%12u\t%12u\t%12u\n", Index[i], sgi_get_start_sector(Index[i]), sgi_get_num_sectors(Index[i]), sgi_get_sysid(Index[i])); } } if (start < lastblock) { if (verbose) printf("Unused gap of %u sectors - sectors %u-%u\n", lastblock - start, start, lastblock-1); gap += lastblock - start; add2freelist(start, lastblock); } /* * Done with arithmetics * Go for details now */ if (verbose) { if (!sgi_get_num_sectors(sgi_get_bootpartition())) { printf("\nThe boot partition does not exist\n"); } if (!sgi_get_num_sectors(sgi_get_swappartition())) { printf("\nThe swap partition does not exist\n"); } else { if ((sgi_get_sysid(sgi_get_swappartition()) != SGI_SWAP) && (sgi_get_sysid(sgi_get_swappartition()) != LINUX_SWAP)) printf("\nThe swap partition has no swap type\n"); } if (sgi_check_bootfile("/unix")) printf("\tYou have chosen an unusual boot file name\n"); } return (gap > 0) ? 1 : (gap == 0) ? 0 : -1; } static int sgi_gaps(void) { /* * returned value is: * = 0 : disk is properly filled to the rim * < 0 : there is an overlap * > 0 : there is still some vacant space */ return verify_sgi(0); } static void sgi_change_sysid(int i, int sys) { if (sgi_get_num_sectors(i) == 0) { /* caught already before, ... */ printf("Sorry you may change the Tag of non-empty partitions\n"); return; } if ((sys != SGI_ENTIRE_DISK) && (sys != SGI_VOLHDR) && (sgi_get_start_sector(i) < 1) ) { read_maybe_empty( "It is highly recommended that the partition at offset 0\n" "is of type \"SGI volhdr\", the IRIX system will rely on it to\n" "retrieve from its directory standalone tools like sash and fx.\n" "Only the \"SGI volume\" entire disk section may violate this.\n" "Type YES if you are sure about tagging this partition differently.\n"); if (strcmp(line_ptr, "YES\n") != 0) return; } sgilabel->partitions[i].id = SGI_SSWAP32(sys); } /* returns partition index of first entry marked as entire disk */ static int sgi_entire(void) { int i; for (i = 0; i < 16; i++) if (sgi_get_sysid(i) == SGI_VOLUME) return i; return -1; } static void sgi_set_partition(int i, unsigned int start, unsigned int length, int sys) { sgilabel->partitions[i].id = SGI_SSWAP32(sys); sgilabel->partitions[i].num_sectors = SGI_SSWAP32(length); sgilabel->partitions[i].start_sector = SGI_SSWAP32(start); set_changed(i); if (sgi_gaps() < 0) /* rebuild freelist */ printf("Partition overlap detected\n"); } static void sgi_set_entire(void) { int n; for (n = 10; n < g_partitions; n++) { if (!sgi_get_num_sectors(n) ) { sgi_set_partition(n, 0, sgi_get_lastblock(), SGI_VOLUME); break; } } } static void sgi_set_volhdr(void) { int n; for (n = 8; n < g_partitions; n++) { if (!sgi_get_num_sectors(n)) { /* * 5 cylinders is an arbitrary value I like * IRIX 5.3 stored files in the volume header * (like sash, symmon, fx, ide) with ca. 3200 * sectors. */ if (g_heads * g_sectors * 5 < sgi_get_lastblock()) sgi_set_partition(n, 0, g_heads * g_sectors * 5, SGI_VOLHDR); break; } } } static void sgi_delete_partition(int i) { sgi_set_partition(i, 0, 0, 0); } static void sgi_add_partition(int n, int sys) { char mesg[256]; unsigned int first = 0, last = 0; if (n == 10) { sys = SGI_VOLUME; } else if (n == 8) { sys = 0; } if (sgi_get_num_sectors(n)) { printf(msg_part_already_defined, n + 1); return; } if ((sgi_entire() == -1) && (sys != SGI_VOLUME)) { printf("Attempting to generate entire disk entry automatically\n"); sgi_set_entire(); sgi_set_volhdr(); } if ((sgi_gaps() == 0) && (sys != SGI_VOLUME)) { printf("The entire disk is already covered with partitions\n"); return; } if (sgi_gaps() < 0) { printf("You got a partition overlap on the disk. Fix it first!\n"); return; } snprintf(mesg, sizeof(mesg), "First %s", str_units(SINGULAR)); while (1) { if (sys == SGI_VOLUME) { last = sgi_get_lastblock(); first = read_int(0, 0, last-1, 0, mesg); if (first != 0) { printf("It is highly recommended that eleventh partition\n" "covers the entire disk and is of type 'SGI volume'\n"); } } else { first = freelist[0].first; last = freelist[0].last; first = read_int(scround(first), scround(first), scround(last)-1, 0, mesg); } if (display_in_cyl_units) first *= units_per_sector; else first = first; /* align to cylinder if you know how ... */ if (!last ) last = isinfreelist(first); if (last != 0) break; printf("You will get a partition overlap on the disk. " "Fix it first!\n"); } snprintf(mesg, sizeof(mesg), " Last %s", str_units(SINGULAR)); last = read_int(scround(first), scround(last)-1, scround(last)-1, scround(first), mesg)+1; if (display_in_cyl_units) last *= units_per_sector; else last = last; /* align to cylinder if You know how ... */ if ( (sys == SGI_VOLUME) && (first != 0 || last != sgi_get_lastblock() ) ) printf("It is highly recommended that eleventh partition\n" "covers the entire disk and is of type 'SGI volume'\n"); sgi_set_partition(n, first, last-first, sys); } #if ENABLE_FEATURE_FDISK_ADVANCED static void create_sgilabel(void) { struct hd_geometry geometry; struct { unsigned int start; unsigned int nsect; int sysid; } old[4]; int i = 0; long longsectors; /* the number of sectors on the device */ int res; /* the result from the ioctl */ int sec_fac; /* the sector factor */ sec_fac = sector_size / 512; /* determine the sector factor */ printf(msg_building_new_label, "SGI disklabel"); sgi_other_endian = BB_LITTLE_ENDIAN; res = ioctl(dev_fd, BLKGETSIZE, &longsectors); if (!ioctl(dev_fd, HDIO_GETGEO, &geometry)) { g_heads = geometry.heads; g_sectors = geometry.sectors; if (res == 0) { /* the get device size ioctl was successful */ g_cylinders = longsectors / (g_heads * g_sectors); g_cylinders /= sec_fac; } else { /* otherwise print error and use truncated version */ g_cylinders = geometry.cylinders; printf( "Warning: BLKGETSIZE ioctl failed on %s. Using geometry cylinder value of %u.\n" "This value may be truncated for devices > 33.8 GB.\n", disk_device, g_cylinders); } } for (i = 0; i < 4; i++) { old[i].sysid = 0; if (valid_part_table_flag(MBRbuffer)) { if (get_part_table(i)->sys_ind) { old[i].sysid = get_part_table(i)->sys_ind; old[i].start = get_start_sect(get_part_table(i)); old[i].nsect = get_nr_sects(get_part_table(i)); printf("Trying to keep parameters of partition %u\n", i); if (SGI_DEBUG) printf("ID=%02x\tSTART=%u\tLENGTH=%u\n", old[i].sysid, old[i].start, old[i].nsect); } } } memset(MBRbuffer, 0, sizeof(MBRbuffer)); /* fields with '//' are already zeroed out by memset above */ sgilabel->magic = SGI_SSWAP32(SGI_LABEL_MAGIC); //sgilabel->boot_part = SGI_SSWAP16(0); sgilabel->swap_part = SGI_SSWAP16(1); //memset(sgilabel->boot_file, 0, 16); strcpy((char*)sgilabel->boot_file, "/unix"); /* sizeof(sgilabel->boot_file) == 16 > 6 */ //sgilabel->devparam.skew = (0); //sgilabel->devparam.gap1 = (0); //sgilabel->devparam.gap2 = (0); //sgilabel->devparam.sparecyl = (0); sgilabel->devparam.pcylcount = SGI_SSWAP16(geometry.cylinders); //sgilabel->devparam.head_vol0 = SGI_SSWAP16(0); /* tracks/cylinder (heads) */ sgilabel->devparam.ntrks = SGI_SSWAP16(geometry.heads); //sgilabel->devparam.cmd_tag_queue_depth = (0); //sgilabel->devparam.unused0 = (0); //sgilabel->devparam.unused1 = SGI_SSWAP16(0); /* sectors/track */ sgilabel->devparam.nsect = SGI_SSWAP16(geometry.sectors); sgilabel->devparam.bytes = SGI_SSWAP16(512); sgilabel->devparam.ilfact = SGI_SSWAP16(1); sgilabel->devparam.flags = SGI_SSWAP32(TRACK_FWD| IGNORE_ERRORS|RESEEK); //sgilabel->devparam.datarate = SGI_SSWAP32(0); sgilabel->devparam.retries_on_error = SGI_SSWAP32(1); //sgilabel->devparam.ms_per_word = SGI_SSWAP32(0); //sgilabel->devparam.xylogics_gap1 = SGI_SSWAP16(0); //sgilabel->devparam.xylogics_syncdelay = SGI_SSWAP16(0); //sgilabel->devparam.xylogics_readdelay = SGI_SSWAP16(0); //sgilabel->devparam.xylogics_gap2 = SGI_SSWAP16(0); //sgilabel->devparam.xylogics_readgate = SGI_SSWAP16(0); //sgilabel->devparam.xylogics_writecont = SGI_SSWAP16(0); //memset( &(sgilabel->directory), 0, sizeof(struct volume_directory)*15 ); //memset( &(sgilabel->partitions), 0, sizeof(struct sgi_partinfo)*16 ); current_label_type = LABEL_SGI; g_partitions = 16; sgi_volumes = 15; sgi_set_entire(); sgi_set_volhdr(); for (i = 0; i < 4; i++) { if (old[i].sysid) { sgi_set_partition(i, old[i].start, old[i].nsect, old[i].sysid); } } } static void sgi_set_xcyl(void) { /* do nothing in the beginning */ } #endif /* FEATURE_FDISK_ADVANCED */ /* _____________________________________________________________ */ static sgiinfo * fill_sgiinfo(void) { sgiinfo *info = xzalloc(sizeof(sgiinfo)); info->magic = SGI_SSWAP32(SGI_INFO_MAGIC); info->b1 = SGI_SSWAP32(-1); info->b2 = SGI_SSWAP16(-1); info->b3 = SGI_SSWAP16(1); /* You may want to replace this string !!!!!!! */ strcpy( (char*)info->scsi_string, "IBM OEM 0662S12 3 30" ); strcpy( (char*)info->serial, "0000" ); info->check1816 = SGI_SSWAP16(18*256 +16 ); strcpy( (char*)info->installer, "Sfx version 5.3, Oct 18, 1994" ); return info; } #endif /* SGI_LABEL */
the_stack_data/98574155.c
#include<stdio.h> #include<stdlib.h> #include<sys/ipc.h> #include<sys/msg.h> #include<string.h> struct msgbuf { int type; char ptr[0]; }; int main(int argc, char *argv[]) { key_t key; key = ftok(argv[1], 100); int msgid; msgid = msgget(key, IPC_CREAT | 0600); pid_t pid; pid = fork(); if (pid == 0) { while (1) { printf("pls input msg to send:"); char buf[128]; fgets(buf, 128, stdin); struct msgbuf *ptr = malloc(sizeof(struct msgbuf) + strlen(buf) + 1); ptr->type = 1; memcpy(ptr->ptr, buf, strlen(buf) + 1); msgsnd(msgid, ptr, strlen(buf) + 1, 0); free(ptr); } } else { struct msgbuf { int type; char ptr[1024]; }; while (1) { struct msgbuf mybuf; memset(&mybuf, '\0', sizeof(mybuf)); msgrcv(msgid, &mybuf, 1024, 2, 0); printf("recv msg:%s\n", mybuf.ptr); } } }
the_stack_data/28262162.c
#include<stdio.h> #include<string.h> int main(int argc, char** argv){ if(argc!=2){ printf("Usage: ./prog input\n"); printf("Hint: ./prog -h\n"); }else if(strcmp("-h",argv[1])==0){ printf("Take a look at values pushed on the stack. Don't forget ascii chars are stored as hex numbers.\n"); }else{ char psswd[5]={'e','a','s','y'}; strcmp(psswd,argv[1])==0?printf("Score!\n"):printf("Fail!\n"); } return 0; }
the_stack_data/111069.c
/*** * This code is a part of EvoApproxLib library (ehw.fit.vutbr.cz/approxlib) distributed under The MIT License. * When used, please cite the following article(s): V. Mrazek, R. Hrbacek, Z. Vasicek and L. Sekanina, "EvoApprox8b: Library of approximate adders and multipliers for circuit design and benchmarking of approximation methods". Design, Automation & Test in Europe Conference & Exhibition (DATE), 2017, Lausanne, 2017, pp. 258-261. doi: 10.23919/DATE.2017.7926993 * This file contains a circuit from evoapprox8b dataset. Note that a new version of library was already published. ***/ #include <stdint.h> #include <stdlib.h> /// Approximate function add8_024 /// Library = EvoApprox8b /// Circuit = add8_024 /// Area (180) = 764 /// Delay (180) = 1.460 /// Power (180) = 230.60 /// Area (45) = 58 /// Delay (45) = 0.570 /// Power (45) = 22.32 /// Nodes = 11 /// HD = 142592 /// MAE = 1.79688 /// MSE = 6.75000 /// MRE = 0.89 % /// WCE = 9 /// WCRE = 200 % /// EP = 78.9 % uint16_t add8_024(uint8_t a, uint8_t b) { uint16_t c = 0; uint8_t n2 = (a >> 1) & 0x1; uint8_t n4 = (a >> 2) & 0x1; uint8_t n6 = (a >> 3) & 0x1; uint8_t n8 = (a >> 4) & 0x1; uint8_t n10 = (a >> 5) & 0x1; uint8_t n12 = (a >> 6) & 0x1; uint8_t n14 = (a >> 7) & 0x1; uint8_t n18 = (b >> 1) & 0x1; uint8_t n20 = (b >> 2) & 0x1; uint8_t n22 = (b >> 3) & 0x1; uint8_t n24 = (b >> 4) & 0x1; uint8_t n26 = (b >> 5) & 0x1; uint8_t n28 = (b >> 6) & 0x1; uint8_t n30 = (b >> 7) & 0x1; uint8_t n40; uint8_t n41; uint8_t n45; uint8_t n46; uint8_t n117; uint8_t n133; uint8_t n182; uint8_t n183; uint8_t n221; uint8_t n232; uint8_t n233; uint8_t n282; uint8_t n283; uint8_t n332; uint8_t n333; uint8_t n382; uint8_t n383; n40 = ~(n20 & n18 & n4); n41 = ~(n20 & n18 & n4); n45 = n40 | n14; n46 = ~n45; n117 = n46; n133 = n4 | n20; n182 = (n6 ^ n22) ^ n117; n183 = (n6 & n22) | (n22 & n117) | (n6 & n117); n221 = n183; n232 = (n8 ^ n24) ^ n221; n233 = (n8 & n24) | (n24 & n221) | (n8 & n221); n282 = (n10 ^ n26) ^ n233; n283 = (n10 & n26) | (n26 & n233) | (n10 & n233); n332 = (n12 ^ n28) ^ n283; n333 = (n12 & n28) | (n28 & n283) | (n12 & n283); n382 = (n14 ^ n30) ^ n333; n383 = (n14 & n30) | (n30 & n333) | (n14 & n333); c |= (n2 & 0x1) << 0; c |= (n41 & 0x1) << 1; c |= (n133 & 0x1) << 2; c |= (n182 & 0x1) << 3; c |= (n232 & 0x1) << 4; c |= (n282 & 0x1) << 5; c |= (n332 & 0x1) << 6; c |= (n382 & 0x1) << 7; c |= (n383 & 0x1) << 8; return c; }
the_stack_data/639024.c
#include <stdio.h> // calls function to cleanup when variable goes out of scope #define CLEAN(f) __attribute__((__cleanup__(f))) void fint(int *x) { printf("%s(%d)\n", __func__, *x); } void fflt(float *x) { printf("%s(%f)\n", __func__, *x); } void test(void) { int a CLEAN(fint); float b CLEAN(fflt); a = 1; b = 2; { int c CLEAN(fint); float d CLEAN(fflt); c = 3; d = 4; { int x CLEAN(fint), y CLEAN(fint); x = 5; y = 6; } } } int main(void) { test(); return 0; }
the_stack_data/49990.c
/* * Copyright (C) 2008-2013 Gil Mendes * * 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. */ /** * @file * @brief POSIX program execution function. */ #include <stdarg.h> #include <unistd.h> #define ARGV_MAX 512 /** * Execute a binary in the PATH. * * If the given path contains a / character, this function will simply call * execve() with the given arguments and the current process' environment. * Otherwise, it will search the PATH for the name given and execute it * if found. * * @param file Name of binary to execute. * @param arg Arguments for process (NULL-terminated argument list). * * @return Does not return on success, -1 on failure. */ int execlp(const char *file, const char *arg, ...) { int i; va_list ap; const char *argv[ARGV_MAX]; argv[0] = arg; va_start(ap, arg); for(i = 1; i < ARGV_MAX; i++) { argv[i] = va_arg(ap, const char *); if(!argv[i]) break; } va_end(ap); return execvp(file, (char *const *)argv); } /** * Execute a binary. * * Executes a binary with the given arguments and the current process' * environment. * * @param path Path to binary to execute. * @param arg Arguments for process (NULL-terminated argument list). * * @return Does not return on success, -1 on failure. */ int execl(const char *path, const char *arg, ...) { int i; va_list ap; const char *argv[ARGV_MAX]; argv[0] = arg; va_start(ap, arg); for(i = 1; i < ARGV_MAX; i++) { argv[i] = va_arg(ap, const char *); if(!argv[i]) break; } va_end(ap); return execv(path, (char *const *)argv); }
the_stack_data/151704395.c
// KASAN: slab-out-of-bounds Read in pfkey_add // https://syzkaller.appspot.com/bug?id=bc59f1de128c03f3674132196315e53fc0a11011 // status:open // autogenerated by syzkaller (http://github.com/google/syzkaller) #define _GNU_SOURCE #include <endian.h> #include <stdint.h> #include <string.h> #include <sys/syscall.h> #include <unistd.h> uint64_t r[1] = {0xffffffffffffffff}; void loop() { long res = 0; res = syscall(__NR_socket, 0xf, 3, 2); if (res != -1) r[0] = res; *(uint64_t*)0x20196fe4 = 0; *(uint32_t*)0x20196fec = 0; *(uint64_t*)0x20196ff4 = 0x200001c0; *(uint64_t*)0x200001c0 = 0x20327f68; memcpy((void*)0x20327f68, "\x02\x03\x00\x00\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x05" "\x00\x06\x00\x00\x00\x00\x00\x0a\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x03\x00\x08\x00\xf9\xff\x00\x00\x02\x00\x00\x00" "\xe0\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x01\x00\x00" "\x00\x00\x00\x00\x00\xfb\x00\x00\x00\x00\x00\x05\x00\x05\x00\x00\x00" "\x00\x00\x0a\x00\x00\x00\x00\x00\x00\x00\xfe\x80\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\xff\x00\x00\x00\x00\x00\x00\x00\x00", 136); *(uint64_t*)0x200001c8 = 0x88; *(uint64_t*)0x20196ffc = 1; *(uint64_t*)0x20197004 = 0; *(uint64_t*)0x2019700c = 0; *(uint32_t*)0x20197014 = 0; syscall(__NR_sendmsg, r[0], 0x20196fe4, 0); } int main() { syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0); loop(); return 0; }
the_stack_data/22013958.c
/* Name: Abhay HM * Date: 13/09/2021 * Info: This program is to calculate 2^N using left shift operator. */ #include <stdio.h> int main(){ unsigned short power = 0; /* Read input from user */ printf("Enter the power[0-31]:"); scanf("%hd",&power); /* Check id power is in range */ if(power >= 0 && power <= 31){ /* Calculate 2^N */ printf("2^%hd = %u\n", power, (1U << power)); } else{ printf("Power is out of range[0-31]\n"); } /* Exit */ return 0; }
the_stack_data/129663.c
#include <stdio.h> int main(){ char O[2]; double M[12][12], soma = 0.0; scanf("%s", &O); for(int i = 0; i<12; i++){ for(int j = 0; j<12; j++){ scanf("%lf", &M[i][j]); if(j+i < 11 && i-j>0) soma += M[i][j]; } } if(O[0] == 'S') printf("%.1lf\n", soma); else if(O[0] == 'M') printf("%.1lf\n", soma/30.0); return 0; }
the_stack_data/560359.c
#include <stdio.h> #include <unistd.h> #include <fcntl.h> int main() { int a = open("shared-file.c", O_RDONLY); if (!fork()) { close(a); return 0; } sleep(2); char buf[3]; read(a, buf, sizeof buf); printf("%c%c%c...\n", buf[0], buf[1], buf[2]); return 0; }
the_stack_data/126675.c
/** * Write a recursive descent parser for: * S -> cAd * A -> ab | a * * S -> cAd * A -> aAp * Ap -> b | $ */ #include <stdio.h> #include <stdlib.h> int match(char **input, char *test) { char *tmp = *input; while(**input == *test && *test != '\0') { (*input)++; test++; } if(*test != '\0') *input = tmp; return *test == '\0'; } int Ap(char **); int A(char **input) { return match(input, "a") && Ap(input); } int Ap(char **input) { return (match(input, "b") && Ap(input)) || 1; } int S(char **input) { return match(input, "c") && A(input) && match(input, "d"); } char accept(char *input) { return S(&input) ? *input : '\0'; } int main(int argc, char *argv[]) { char buffer[1024]; fgets(buffer, sizeof(buffer), stdin); if(accept(buffer) == '\n') { puts("Input string matched.\n"); } else { puts("Input string did not match.\n"); } return EXIT_SUCCESS; }
the_stack_data/107951877.c
/* Space Plumber Angel Ortega <[email protected]> This software is released into the public domain. NO WARRANTY. See file LICENSE for details. */ #include <stdio.h> #include <stdlib.h> /* estructura de la paleta de color */ struct palette { unsigned char r; unsigned char g; unsigned char b; }; struct palette pal[256]; int r_perc = 59; int g_perc = 59; int b_perc = 59; int LoadPalette(char *palfile, struct palette *pal) /* carga la paleta */ { int n; FILE *f; char lin[80]; unsigned int r, g, b; if ((f = fopen(palfile, "r")) != NULL) { /* lee la primera línea (JASC-PAL), la segunda (versión) y la tercera (256) */ fgets(lin, sizeof(lin) - 1, f); fgets(lin, sizeof(lin) - 1, f); fgets(lin, sizeof(lin) - 1, f); for (n = 0; n < 256; n++) { if (fscanf(f, "%u %u %u\n", &r, &g, &b) != 3) break; pal->r = (unsigned char) r; pal->g = (unsigned char) g; pal->b = (unsigned char) b; pal++; } for (; n < 256; n++) { pal->r = pal->g = pal->b = 0; pal++; } fclose(f); return (1); } return (0); } int SavePalette(char *palfile, struct palette *pal) /* guarda la paleta */ { FILE *f; char lin[80]; int n; if ((f = fopen(palfile, "w")) != NULL) { fprintf(f, "JASC-PAL\n"); fprintf(f, "0100\n"); fprintf(f, "256\n"); for (n = 0; n < 256; n++, pal++) fprintf(f, "%u %u %u\n", pal->r, pal->g, pal->b); fclose(f); } return (0); } int colcmp2(const void *v1, const void *v2) { int dif; struct palette *c1, *c2; c1 = (struct palette *) v1; c2 = (struct palette *) v2; dif = c1->r - c2->r; if (abs(c1->g - c2->g) > abs(dif)) dif = c1->g - c2->g; if (abs(c1->b - c2->b) > abs(dif)) dif = c1->b - c2->b; return (dif); } int colcmp(const void *v1, const void *v2) { int d1, d2; struct palette *c1, *c2; c1 = (struct palette *) v1; c2 = (struct palette *) v2; d1 = (c1->r + c1->g + c1->b) / 3; d2 = (c2->r + c2->g + c2->b) / 3; return (d1 - d2); } int colcmp3(const void *v1, const void *v2) { int d1, d2; struct palette *c1, *c2; c1 = (struct palette *) v1; c2 = (struct palette *) v2; d1 = c1->g << 16 | c1->r << 8 | c1->b; d2 = c2->g << 16 | c2->r << 8 | c2->b; return (d1 - d2); } unsigned char Degrade(unsigned char col1, unsigned char col2, int perc) { int i; i = (int) col1 + (int) col2; i /= 2; i *= perc; i /= 100; /* i*=6; i/=8; */ return ((unsigned char) i); } int PrepPalette(struct palette *pal) { int n, m; qsort(pal, 256, sizeof(struct palette), colcmp3); for (n = 255, m = 127; n > 127; n -= 2, m--) { pal[m].r = Degrade(pal[n].r, pal[n - 1].r, r_perc); pal[m].g = Degrade(pal[n].g, pal[n - 1].g, g_perc); pal[m].b = Degrade(pal[n].b, pal[n - 1].b, b_perc); } for (n = 127, m = 63; n > 63; n -= 2, m--) { pal[m].r = Degrade(pal[n].r, pal[n - 1].r, r_perc); pal[m].g = Degrade(pal[n].g, pal[n - 1].g, g_perc); pal[m].b = Degrade(pal[n].b, pal[n - 1].b, b_perc); } for (n = 63, m = 31; n > 31; n -= 2, m--) { pal[m].r = Degrade(pal[n].r, pal[n - 1].r, r_perc); pal[m].g = Degrade(pal[n].g, pal[n - 1].g, g_perc); pal[m].b = Degrade(pal[n].b, pal[n - 1].b, b_perc); } for (n = 31, m = 15; n > 15; n -= 2, m--) { pal[m].r = Degrade(pal[n].r, pal[n - 1].r, r_perc); pal[m].g = Degrade(pal[n].g, pal[n - 1].g, g_perc); pal[m].b = Degrade(pal[n].b, pal[n - 1].b, b_perc); } for (n = 15, m = 7; n > 7; n -= 2, m--) { pal[m].r = Degrade(pal[n].r, pal[n - 1].r, r_perc); pal[m].g = Degrade(pal[n].g, pal[n - 1].g, g_perc); pal[m].b = Degrade(pal[n].b, pal[n - 1].b, b_perc); } for (n = 7, m = 3; n > 3; n -= 2, m--) { pal[m].r = Degrade(pal[n].r, pal[n - 1].r, r_perc); pal[m].g = Degrade(pal[n].g, pal[n - 1].g, g_perc); pal[m].b = Degrade(pal[n].b, pal[n - 1].b, b_perc); } } int main(int argc, char *argv[]) { int n, r, g, b; if (argc != 3) { printf("\nSpace Plumber Palette Generator - Angel Ortega\n\n"); printf("Usage: xpal {org.pal} {des.pal}\n"); return (1); } if (!LoadPalette(argv[1], pal)) { perror("LoadPalette"); return (1); } PrepPalette(pal); SavePalette(argv[2], pal); return (0); }
the_stack_data/101133.c
/* * Copyright 2016 The Emscripten Authors. All rights reserved. * Emscripten is available under two separate licenses, the MIT license and the * University of Illinois/NCSA Open Source License. Both these licenses can be * found in the LICENSE file. */ #include <stdio.h> #include <stdlib.h> #include <stdarg.h> int arg_n(int n, va_list ap) { // similar to the implementation of vfscanf va_list ap2; va_copy(ap2, ap); for (int i = 0; i < n; ++i) { va_arg(ap2, int); } int ret = va_arg(ap2, int); va_end(ap2); return ret; } void vary(int n, ...) { va_list v; va_start(v, n); for (int i = 0; i < n; ++i) { if (i != 0) { printf(", "); } printf("%d", arg_n(i, v)); } printf("\n"); va_end(v); } int main() { int x = 1; int y = 2; int z = 3; vary(3, x, y, z); vary(2, x, z); vary(1, x); return 0; }
the_stack_data/1211783.c
/* This code may be used by anyone. Errors and improvements should be reported to the author */ /* Tested with gzip 1.2.1 and gzip 1.2.2 */ #include <zlib.h> #include <malloc.h> #include <stdio.h> /** Buffersize for compress/decompress **/ #define INCREASE 10240 #define uint32_t unsigned int #ifndef max #define max(x,y) ((x) > (y) ? (x) : (y)) #endif extern char *base64(const unsigned char *input, int length); /** Compress data by GZIP in Memory @param source Pointer to the data to be compressed @param sourcelen len of sourcedata @param target Pointer to the result. Has to be freed by 'free' @param targetlen Len of targetdata @return always 0 **/ int Compress(const unsigned char *source, unsigned int sourcelen, unsigned char** target, unsigned int *targetlen) { z_stream c_stream; memset(&c_stream, 0, sizeof(c_stream)); int ret = 0; int err; int alloclen = max(sourcelen, INCREASE); c_stream.zalloc = NULL; c_stream.zfree = NULL; c_stream.opaque = NULL; *target = (unsigned char *) malloc(alloclen); // Initialisation, so that GZIP will be created if (deflateInit2(&c_stream,Z_BEST_COMPRESSION,Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY) == Z_OK) { c_stream.next_in = (Bytef*)source; c_stream.avail_in = sourcelen; c_stream.next_out = *target; c_stream.avail_out = alloclen; while (c_stream.total_in != sourcelen && c_stream.total_out < *targetlen) { err = deflate(&c_stream, Z_NO_FLUSH); // CHECK_ERR(err, "deflate"); if (c_stream.avail_out == 0) { // Alloc new memory int now = alloclen; alloclen += alloclen / 10 + INCREASE; *target = (unsigned char *) realloc(*target, alloclen); c_stream.next_out = *target + now; c_stream.avail_out = alloclen - now; } } // Finish the stream for (;;) { err = deflate(&c_stream, Z_FINISH); if (err == Z_STREAM_END) break; if (c_stream.avail_out == 0) { // Alloc new memory int now = alloclen; alloclen += alloclen / 10 + INCREASE; *target = (unsigned char *) realloc(*target, alloclen); c_stream.next_out = *target + now; c_stream.avail_out = alloclen - now; } // CHECK_ERR(err, "deflate"); } err = deflateEnd(&c_stream); // CHECK_ERR(err, "deflateEnd"); } *targetlen = c_stream.total_out; // free remaining memory *target = (unsigned char *) realloc(*target, *targetlen); return ret; } /** Inflate data with GZIP @param source Pointer to the compressed data @param sourcelen Len of compressed data @param target Pointer to the inflated data, has to be freed with 'free' @param targetlen Len of inflated data @return always 0 **/ int Decompress(const unsigned char *source, unsigned int sourcelen, unsigned char **target, unsigned int *targetlen) { z_stream c_stream; memset(&c_stream, 0, sizeof(c_stream)); int ret = 0; int err; int alloclen = max(sourcelen * 2, INCREASE); c_stream.zalloc = NULL; c_stream.zfree = NULL; c_stream.opaque = NULL; *target = (unsigned char *) malloc(alloclen+1); *targetlen = 0; if (inflateInit2(&c_stream, 15 + 16) == Z_OK) { c_stream.next_in = (Bytef*)source; c_stream.avail_in = sourcelen; c_stream.next_out = *target; c_stream.avail_out = alloclen; while (c_stream.total_in != sourcelen && c_stream.total_out < *targetlen) { err = inflate(&c_stream, Z_NO_FLUSH); // CHECK_ERR(err, "deflate"); if (c_stream.avail_out == 0) { // Alloc new memory int now = alloclen; alloclen += alloclen / 10 + INCREASE; *target = (unsigned char *) realloc(*target, alloclen+1); c_stream.next_out = *target + now; c_stream.avail_out = alloclen - now; } } // Finish the stream for (;;) { err = inflate(&c_stream, Z_FINISH); if (err == Z_STREAM_END) break; if (c_stream.avail_out == 0) { // alloc new memory int now = alloclen; alloclen += alloclen / 10 + INCREASE; *target = (unsigned char *) realloc(*target, alloclen+1); c_stream.next_out = *target + now; c_stream.avail_out = alloclen - now; } // CHECK_ERR(err, "deflate"); } err = inflateEnd(&c_stream); // CHECK_ERR(err, "deflateEnd"); } *targetlen = c_stream.total_out; // Free remaining memory *target = (unsigned char *) realloc(*target, *targetlen); return 0; } int main(int argc, char *argv[]) { //unsigned char* szSrc= "hello world"; unsigned char* szDest = NULL; char input[12] = {0x68,0x65,0x6C,0x6C,0x6F,0x20,0x77,0x6F,0x72,0x6C,0x64,'\0'}; unsigned int nDest = 0; printf("base64(gzip(%s))\n", input); Compress(input, strlen(input), &szDest, &nDest); printf("from %d to %d\n", strlen(input), nDest); //char szLen[2] = {0x0B, '\0'}; //char* lenOut = base64(szLen, strlen(szLen)); //printf("Base64: %s\n", lenOut); //free(lenOut); char* output = base64(szDest, nDest); printf("Base64: %s\n", output); free(output); }
the_stack_data/145452758.c
// general protection fault in xsk_poll // https://syzkaller.appspot.com/bug?id=a2176c353f66aa0dab0a37c901fb010771a9c3b2 // status:open // autogenerated by syzkaller (https://github.com/google/syzkaller) #define _GNU_SOURCE #include <endian.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/syscall.h> #include <sys/types.h> #include <unistd.h> uint64_t r[1] = {0xffffffffffffffff}; int main(void) { syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0); intptr_t res = 0; res = syscall(__NR_socket, 0x2c, 3, 0); if (res != -1) r[0] = res; *(uint32_t*)0x20000280 = r[0]; *(uint16_t*)0x20000284 = 0; *(uint16_t*)0x20000286 = 0; syscall(__NR_ppoll, 0x20000280, 1, 0, 0, 0); return 0; }
the_stack_data/721283.c
#include<stdio.h> long long H(long long,long long); long long a[101],l[101],r[101]; int main(){ int n,k,i,j,x; long long N[101]={0},M[101]={0},K[101]; scanf("%d%d",&n,&k); for(i=0;i<n;i++) scanf("%lld",&a[i]); for(i=0;i<k;i++) scanf("%lld%lld",&l[i],&r[i]); for(i=0;i<k;i++) { M[i]=1; for(j=l[i];j<=r[i];j++) { N[i]+=a[j]; M[i]=(M[i]%n)*a[j]; } N[i]=N[i]%n; M[i]=M[i]%n; if(N[i]>=M[i]) K[i]=H(M[i],N[i]); else K[i]=H(N[i],M[i]); } for(i=0;i<k;i++) printf("%lld\n",K[i]); return 0; } long long H(long long min,long long max){ int i; long long mid=a[min]; for(i=min;i<max;i++) mid=mid^a[i+1]; return mid; }
the_stack_data/190769229.c
#include<stdint.h> #include<stdlib.h> #include<string.h> unsigned int conta_spazi(const char* s) { size_t i, space = 0; size_t lenght = strlen(s); for (i = 0; i < lenght; ++i) { if (s[i] == ' ') ++space; } return space; }
the_stack_data/92324617.c
#include <stdio.h> #include <stdlib.h> #include <sys/syscall.h> /* Definition of SYS_* constants */ #include <unistd.h> void test_func(char *name) { printf("%s", name); } void test_func2(int num) { char *test; if(num > 5) test = malloc(sizeof(int) * num); else test = malloc(sizeof(char) * num); free(test); } void test_func3(int num) { for(int i=0;i<num; i++) { // asm volatile("syscall" : : "a"(1), "D"(0), "S"(str), "d"(13)); asm("syscall" : : "a"(1), "D"(0)); } } int main() { puts("Hello World!\n"); test_func("test\n"); test_func2(5); test_func2(7); test_func3(10); return 0; }
the_stack_data/46986.c
#include <math.h> #include <stdint.h> int __fpclassifyf(float x) { union { float f; uint32_t i; } u = {x}; int e = u.i >> 23 & 0xff; if (!e) return u.i << 1 ? FP_SUBNORMAL : FP_ZERO; if (e == 0xff) return u.i << 9 ? FP_NAN : FP_INFINITE; return FP_NORMAL; }
the_stack_data/100140675.c
#include<stdio.h> void main() { int a,b,c; printf("ENTER 3 NUMBERS\n"); scanf("%d%d%d",&a,&b,&c); if((a>b)&&(a>c)) printf("%d IS GREATEST\n",a); else if((b>a)&&(b>c)) printf("%d IS GREATEST\n",b); else printf("%d IS GREATEST\n",c); }
the_stack_data/1228201.c
extern void __VERIFIER_error() __attribute__ ((__noreturn__)); extern void __VERIFIER_assume(int); void __VERIFIER_assert(int cond) { if(!(cond)) { ERROR: __VERIFIER_error(); } } extern int __VERIFIER_nondet_int(void); int N; int main() { N = __VERIFIER_nondet_int(); if(N <= 0) return 1; int i; long sum; long long a[N]; sum = 0; for(i=0; i<N; i++) { a[i] = 1; } for(i=0; i<N; i++) { sum = sum + a[i]; } for(i=0; i<N; i++) { a[i] = a[i] + sum; } for(i=0; i<N; i++) { __VERIFIER_assert(a[i] == N + 1); } return 1; }
the_stack_data/718701.c
#include <stdio.h> int main() { int grades[2][5] = { {80, 70, 65, 89, 90}, {85, 80, 80, 82, 87} }; float average; int i; int j; for (i = 0; i < 2; i++) { average = 0; for (j = 0; j < 5; j++) { average += grades[i][j]; } average /= 5.0; printf("The average marks obtained in subject %d is: %2f\n", i, average); } return 0; }
the_stack_data/558553.c
/*- * Copyright (c) 2002 Kyle Martin <[email protected]> * 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. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. * * $FreeBSD: src/lib/libc/gen/ulimit.c,v 1.3.34.1.6.1 2010/12/21 17:09:25 kensmith Exp $ */ #include <sys/types.h> #include <sys/time.h> #include <sys/resource.h> #include <errno.h> #include <limits.h> #include <stdarg.h> #include <ulimit.h> long ulimit(int cmd, ...) { struct rlimit limit; va_list ap; long arg; if (cmd == UL_GETFSIZE) { if (getrlimit(RLIMIT_FSIZE, &limit) == -1) return (-1); limit.rlim_cur /= 512; if (limit.rlim_cur > LONG_MAX) return (LONG_MAX); return ((long)limit.rlim_cur); } else if (cmd == UL_SETFSIZE) { va_start(ap, cmd); arg = va_arg(ap, long); va_end(ap); limit.rlim_max = limit.rlim_cur = (rlim_t)arg * 512; /* The setrlimit() function sets errno to EPERM if needed. */ if (setrlimit(RLIMIT_FSIZE, &limit) == -1) return (-1); if (arg * 512 > LONG_MAX) return (LONG_MAX); return (arg); } else { errno = EINVAL; return (-1); } }
the_stack_data/125141912.c
/* SENHAS DE 3 DÍGITOS */ #include <stdio.h> #include <stdlib.h> #define CLIENTES 10 #define MAX 999 #define MIN 100 #include <time.h> int main(void) { int senhas[CLIENTES], indice, fracas = 0, fortes = 0, menor = 999999999, maior = -999999999; srand(time(NULL)); for(indice = 0; indice < CLIENTES; indice++){ // RAND: [MÍN, MÁX]: [100, 999] senhas[indice] = rand() % (MAX - MIN - 1) + MIN; } printf("Sugestão de senhas: \n"); for (indice = 0; indice < CLIENTES; indice++){ printf("Senha %i: %i\n", indice + 1, senhas[indice]); } // Relatório: Informação // LETRA A: Senhas fracas e fortes (ímpares E NÃO múltiplas de 17): Absolutos / Relativos (%) for (indice = 0; indice < CLIENTES; indice++){ if (senhas[indice] % 2 != 0 && senhas[indice] % 17 != 0) fortes++; else fracas++; } printf("\nSenhas Fracas: %i = %.1f %%\n", fracas, fracas*100.0/(fracas + fortes)); printf("Senhas Fortes: %i = %.1f %%\n", fortes, fortes*100.0/(fracas + fortes)); // LETRA B: Menor / Maior senha sorteada do vetor for (indice = 0; indice < CLIENTES; indice++){ if (senhas[indice] < menor) menor = senhas[indice]; else if (senhas[indice] > maior) maior = senhas[indice]; } printf("\nMaior senha: %i\n", maior); printf("Menor senha: %i", menor); return 0; }
the_stack_data/139739.c
#include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <err.h> #include <errno.h> #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <string.h> #include <unistd.h> static void usage(const char *cmd) { fprintf(stderr, "%s -4 ip4 -p port [-r]\n", cmd); exit(1); } int main(int argc, char *argv[]) { struct sockaddr_in in, in2; int s, opt, n, reuseport; uint8_t buf[18]; memset(&in, 0, sizeof(in)); in.sin_family = AF_INET; reuseport = 0; while ((opt = getopt(argc, argv, "4:p:r")) != -1) { switch (opt) { case '4': if (inet_pton(AF_INET, optarg, &in.sin_addr) <= 0) usage(argv[0]); break; case 'p': in.sin_port = strtol(optarg, NULL, 10); in.sin_port = htons(in.sin_port); break; case 'r': reuseport = 1; break; default: usage(argv[0]); } } if (in.sin_addr.s_addr == INADDR_ANY || in.sin_port == 0) usage(argv[0]); s = socket(AF_INET, SOCK_DGRAM, 0); if (s < 0) err(2, "socket failed"); if (reuseport) { if (setsockopt(s, SOL_SOCKET, SO_REUSEPORT, &reuseport, sizeof(reuseport)) < 0) err(2, "setsockopt SO_REUSEPORT failed"); } if (connect(s, (const struct sockaddr *)&in, sizeof(in)) < 0) err(2, "connect failed"); memset(&in2, 0, sizeof(in2)); in2.sin_family = AF_UNSPEC; if (connect(s, (const struct sockaddr *)&in2, sizeof(in2)) < 0) { int error = errno; if (error != EAFNOSUPPORT) errc(2, error, "di-connect failed"); } n = sendto(s, buf, sizeof(buf), 0, (const struct sockaddr *)&in, sizeof(in)); if (n < 0) err(2, "sendto failed"); else if (n != (int)sizeof(buf)) errx(2, "sent truncated data %d", n); n = read(s, buf, sizeof(buf)); if (n < 0) err(2, "read failed"); printf("read %d, done\n", n); exit(0); }
the_stack_data/95450731.c
/* { dg-do compile } */ /* { dg-options "-O2 -fdump-tree-vrp1" } */ /* LLVM LOCAL test not applicable */ /* { dg-require-fdump "" } */ /* { dg-require-effective-target int32plus } */ void fn_call (int); int h(int, int); void t() { int i; int x; for( i = 0; i < 100000000; i++ ){ fn_call (i < 100000000); } } /* { dg-final { scan-tree-dump-times "fn_call \\(1\\)" 1 "vrp1" } } */ /* { dg-final { cleanup-tree-dump "vrp1" } } */
the_stack_data/31288.c
#include <stdio.h> #include <limits.h> void itoa(int n, char s[]); int main() { int n = 0; char s[80]; while (n != -1) { printf(">"); scanf("%d",&n); itoa(n, s); printf(" %s\n", s); } } void itoa(int n, char s[]) { int sign; int i = 0; int j; char c; if ((sign = n) >= 0) { s[i++] = n % 10 + '0'; n /= 10; } else { s[i++] = -(n % 10) + '0'; n /= -10; } while (n > 0) { s[i++] = n % 10 + '0'; n /= 10; } if (sign < 0) s[i++] = '-'; s[i--] = '\0'; /* reversing string */ for (j = 0; j < i; j++, i--) c = s[j], s[j] = s[i], s[i] = c; }
the_stack_data/32951142.c
/* * This program adds two numbers without using any * airthmaetic operators. * TODO:CODE * TODO:DOC * TODO:TESTS */ #include<stdio.h> #include<assert.h> int add_two_numbs_without_using_airthmetic_ops (int a, int b) { int index; int result, carry; int a_bit_index; int b_bit_index; result = 0; for (index = 0; index < sizeof(int); ++index) { a_bit_index = a & (1 << index); b_bit_index = b & (1 << index); carry = b_bit_index & a_bit_index; } }
the_stack_data/30100.c
#include <stdio.h> typedef long long int64; // прямоугольник struct rectangle { int64 x, y; // ширина, высота }; struct rectangle r; double area(struct rectangle r) { return (r.x * r.y); } int main() { r.x = 5; r.y = 10; double p; p = area(r); printf("%f\n", p); return 0; }
the_stack_data/496726.c
int maximum(int a, int b) { long long diff = a; diff -= b; int sign = (diff >> 63) & 1; // a >= b, a - b >= 0, sign = 0 return (a * (sign ^ 1)) | (b * sign); }
the_stack_data/17646.c
/*15. Design and develop a function reverses(s) in C to reverse the string s in place. Invoke this function from the main for different strings and print the original and reversed strings. */ #include <stdio.h> #include <string.h> void reverse(char s[]) { char temp; int i,len; len = strlen(s)-1; for(i=0;i<strlen(s)/2;i++) { temp=s[i]; s[i]=s[len]; s[len]=temp; len--; } printf("the reversed string is = %s",s); } int main() { char s[10]; int i; printf("Enter String : "); scanf("%s",s); printf("the original string is=%s\n",s); reverse(s); return 0; }
the_stack_data/247019037.c
/* f2c.h -- Standard Fortran to C header file */ /** barf [ba:rf] 2. "He suggested using FORTRAN, and everybody barfed." - From The Shogakukan DICTIONARY OF NEW ENGLISH (Second edition) */ #ifndef F2C_INCLUDE #define F2C_INCLUDE #include <math.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <complex.h> #ifdef complex #undef complex #endif #ifdef I #undef I #endif #if defined(_WIN64) typedef long long BLASLONG; typedef unsigned long long BLASULONG; #else typedef long BLASLONG; typedef unsigned long BLASULONG; #endif #ifdef LAPACK_ILP64 typedef BLASLONG blasint; #if defined(_WIN64) #define blasabs(x) llabs(x) #else #define blasabs(x) labs(x) #endif #else typedef int blasint; #define blasabs(x) abs(x) #endif typedef blasint integer; typedef unsigned int uinteger; typedef char *address; typedef short int shortint; typedef float real; typedef double doublereal; typedef struct { real r, i; } complex; typedef struct { doublereal r, i; } doublecomplex; static inline _Complex float Cf(complex *z) {return z->r + z->i*_Complex_I;} static inline _Complex double Cd(doublecomplex *z) {return z->r + z->i*_Complex_I;} static inline _Complex float * _pCf(complex *z) {return (_Complex float*)z;} static inline _Complex double * _pCd(doublecomplex *z) {return (_Complex double*)z;} #define pCf(z) (*_pCf(z)) #define pCd(z) (*_pCd(z)) typedef int logical; typedef short int shortlogical; typedef char logical1; typedef char integer1; #define TRUE_ (1) #define FALSE_ (0) /* Extern is for use with -E */ #ifndef Extern #define Extern extern #endif /* I/O stuff */ typedef int flag; typedef int ftnlen; typedef int ftnint; /*external read, write*/ typedef struct { flag cierr; ftnint ciunit; flag ciend; char *cifmt; ftnint cirec; } cilist; /*internal read, write*/ typedef struct { flag icierr; char *iciunit; flag iciend; char *icifmt; ftnint icirlen; ftnint icirnum; } icilist; /*open*/ typedef struct { flag oerr; ftnint ounit; char *ofnm; ftnlen ofnmlen; char *osta; char *oacc; char *ofm; ftnint orl; char *oblnk; } olist; /*close*/ typedef struct { flag cerr; ftnint cunit; char *csta; } cllist; /*rewind, backspace, endfile*/ typedef struct { flag aerr; ftnint aunit; } alist; /* inquire */ typedef struct { flag inerr; ftnint inunit; char *infile; ftnlen infilen; ftnint *inex; /*parameters in standard's order*/ ftnint *inopen; ftnint *innum; ftnint *innamed; char *inname; ftnlen innamlen; char *inacc; ftnlen inacclen; char *inseq; ftnlen inseqlen; char *indir; ftnlen indirlen; char *infmt; ftnlen infmtlen; char *inform; ftnint informlen; char *inunf; ftnlen inunflen; ftnint *inrecl; ftnint *innrec; char *inblank; ftnlen inblanklen; } inlist; #define VOID void union Multitype { /* for multiple entry points */ integer1 g; shortint h; integer i; /* longint j; */ real r; doublereal d; complex c; doublecomplex z; }; typedef union Multitype Multitype; struct Vardesc { /* for Namelist */ char *name; char *addr; ftnlen *dims; int type; }; typedef struct Vardesc Vardesc; struct Namelist { char *name; Vardesc **vars; int nvars; }; typedef struct Namelist Namelist; #define abs(x) ((x) >= 0 ? (x) : -(x)) #define dabs(x) (fabs(x)) #define f2cmin(a,b) ((a) <= (b) ? (a) : (b)) #define f2cmax(a,b) ((a) >= (b) ? (a) : (b)) #define dmin(a,b) (f2cmin(a,b)) #define dmax(a,b) (f2cmax(a,b)) #define bit_test(a,b) ((a) >> (b) & 1) #define bit_clear(a,b) ((a) & ~((uinteger)1 << (b))) #define bit_set(a,b) ((a) | ((uinteger)1 << (b))) #define abort_() { sig_die("Fortran abort routine called", 1); } #define c_abs(z) (cabsf(Cf(z))) #define c_cos(R,Z) { pCf(R)=ccos(Cf(Z)); } #define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);} #define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);} #define c_exp(R, Z) {pCf(R) = cexpf(Cf(Z));} #define c_log(R, Z) {pCf(R) = clogf(Cf(Z));} #define c_sin(R, Z) {pCf(R) = csinf(Cf(Z));} //#define c_sqrt(R, Z) {*(R) = csqrtf(Cf(Z));} #define c_sqrt(R, Z) {pCf(R) = csqrtf(Cf(Z));} #define d_abs(x) (fabs(*(x))) #define d_acos(x) (acos(*(x))) #define d_asin(x) (asin(*(x))) #define d_atan(x) (atan(*(x))) #define d_atn2(x, y) (atan2(*(x),*(y))) #define d_cnjg(R, Z) { pCd(R) = conj(Cd(Z)); } #define r_cnjg(R, Z) { pCf(R) = conj(Cf(Z)); } #define d_cos(x) (cos(*(x))) #define d_cosh(x) (cosh(*(x))) #define d_dim(__a, __b) ( *(__a) > *(__b) ? *(__a) - *(__b) : 0.0 ) #define d_exp(x) (exp(*(x))) #define d_imag(z) (cimag(Cd(z))) #define r_imag(z) (cimag(Cf(z))) #define d_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define r_int(__x) (*(__x)>0 ? floor(*(__x)) : -floor(- *(__x))) #define d_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define r_lg10(x) ( 0.43429448190325182765 * log(*(x)) ) #define d_log(x) (log(*(x))) #define d_mod(x, y) (fmod(*(x), *(y))) #define u_nint(__x) ((__x)>=0 ? floor((__x) + .5) : -floor(.5 - (__x))) #define d_nint(x) u_nint(*(x)) #define u_sign(__a,__b) ((__b) >= 0 ? ((__a) >= 0 ? (__a) : -(__a)) : -((__a) >= 0 ? (__a) : -(__a))) #define d_sign(a,b) u_sign(*(a),*(b)) #define r_sign(a,b) u_sign(*(a),*(b)) #define d_sin(x) (sin(*(x))) #define d_sinh(x) (sinh(*(x))) #define d_sqrt(x) (sqrt(*(x))) #define d_tan(x) (tan(*(x))) #define d_tanh(x) (tanh(*(x))) #define i_abs(x) abs(*(x)) #define i_dnnt(x) ((integer)u_nint(*(x))) #define i_len(s, n) (n) #define i_nint(x) ((integer)u_nint(*(x))) #define i_sign(a,b) ((integer)u_sign((integer)*(a),(integer)*(b))) #define pow_dd(ap, bp) ( pow(*(ap), *(bp))) #define pow_si(B,E) spow_ui(*(B),*(E)) #define pow_ri(B,E) spow_ui(*(B),*(E)) #define pow_di(B,E) dpow_ui(*(B),*(E)) #define pow_zi(p, a, b) {pCd(p) = zpow_ui(Cd(a), *(b));} #define pow_ci(p, a, b) {pCf(p) = cpow_ui(Cf(a), *(b));} #define pow_zz(R,A,B) {pCd(R) = cpow(Cd(A),*(B));} #define s_cat(lpp, rpp, rnp, np, llp) { ftnlen i, nc, ll; char *f__rp, *lp; ll = (llp); lp = (lpp); for(i=0; i < (int)*(np); ++i) { nc = ll; if((rnp)[i] < nc) nc = (rnp)[i]; ll -= nc; f__rp = (rpp)[i]; while(--nc >= 0) *lp++ = *(f__rp)++; } while(--ll >= 0) *lp++ = ' '; } #define s_cmp(a,b,c,d) ((integer)strncmp((a),(b),f2cmin((c),(d)))) #define s_copy(A,B,C,D) { int __i,__m; for (__i=0, __m=f2cmin((C),(D)); __i<__m && (B)[__i] != 0; ++__i) (A)[__i] = (B)[__i]; } #define sig_die(s, kill) { exit(1); } #define s_stop(s, n) {exit(0);} static char junk[] = "\n@(#)LIBF77 VERSION 19990503\n"; #define z_abs(z) (cabs(Cd(z))) #define z_exp(R, Z) {pCd(R) = cexp(Cd(Z));} #define z_sqrt(R, Z) {pCd(R) = csqrt(Cd(Z));} #define myexit_() break; #define mycycle() continue; #define myceiling(w) {ceil(w)} #define myhuge(w) {HUGE_VAL} //#define mymaxloc_(w,s,e,n) {if (sizeof(*(w)) == sizeof(double)) dmaxloc_((w),*(s),*(e),n); else dmaxloc_((w),*(s),*(e),n);} #define mymaxloc(w,s,e,n) {dmaxloc_(w,*(s),*(e),n)} /* procedure parameter types for -A and -C++ */ #define F2C_proc_par_types 1 #ifdef __cplusplus typedef logical (*L_fp)(...); #else typedef logical (*L_fp)(); #endif static float spow_ui(float x, integer n) { float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static double dpow_ui(double x, integer n) { double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static _Complex float cpow_ui(_Complex float x, integer n) { _Complex float pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static _Complex double zpow_ui(_Complex double x, integer n) { _Complex double pow=1.0; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x = 1/x; for(u = n; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer pow_ii(integer x, integer n) { integer pow; unsigned long int u; if (n <= 0) { if (n == 0 || x == 1) pow = 1; else if (x != -1) pow = x == 0 ? 1/x : 0; else n = -n; } if ((n > 0) || !(n == 0 || x == 1 || x != -1)) { u = n; for(pow = 1; ; ) { if(u & 01) pow *= x; if(u >>= 1) x *= x; else break; } } return pow; } static integer dmaxloc_(double *w, integer s, integer e, integer *n) { double m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static integer smaxloc_(float *w, integer s, integer e, integer *n) { float m; integer i, mi; for(m=w[s-1], mi=s, i=s+1; i<=e; i++) if (w[i-1]>m) mi=i ,m=w[i-1]; return mi-s+1; } static inline void cdotc_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i])) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conjf(Cf(&x[i*incx])) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i])) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += conj(Cd(&x[i*incx])) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex float zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i]) * Cf(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cf(&x[i*incx]) * Cf(&y[i*incy]); } } pCf(z) = zdotc; } static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; _Complex double zdotc = 0.0; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i]) * Cd(&y[i]); } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc += Cd(&x[i*incx]) * Cd(&y[i*incy]); } } pCd(z) = zdotc; } #endif /* -- translated by f2c (version 20000121). You must link the resulting object file with the libraries: -lf2c -lm (in that order) */ /* Table of constant values */ static integer c__1 = 1; /* > \brief \b ZLANTP returns the value of the 1-norm, or the Frobenius norm, or the infinity norm, or the ele ment of largest absolute value of a triangular matrix supplied in packed form. */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* > \htmlonly */ /* > Download ZLANTP + dependencies */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/zlantp. f"> */ /* > [TGZ]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/zlantp. f"> */ /* > [ZIP]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/zlantp. f"> */ /* > [TXT]</a> */ /* > \endhtmlonly */ /* Definition: */ /* =========== */ /* DOUBLE PRECISION FUNCTION ZLANTP( NORM, UPLO, DIAG, N, AP, WORK ) */ /* CHARACTER DIAG, NORM, UPLO */ /* INTEGER N */ /* DOUBLE PRECISION WORK( * ) */ /* COMPLEX*16 AP( * ) */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > */ /* > ZLANTP returns the value of the one norm, or the Frobenius norm, or */ /* > the infinity norm, or the element of largest absolute value of a */ /* > triangular matrix A, supplied in packed form. */ /* > \endverbatim */ /* > */ /* > \return ZLANTP */ /* > \verbatim */ /* > */ /* > ZLANTP = ( f2cmax(abs(A(i,j))), NORM = 'M' or 'm' */ /* > ( */ /* > ( norm1(A), NORM = '1', 'O' or 'o' */ /* > ( */ /* > ( normI(A), NORM = 'I' or 'i' */ /* > ( */ /* > ( normF(A), NORM = 'F', 'f', 'E' or 'e' */ /* > */ /* > where norm1 denotes the one norm of a matrix (maximum column sum), */ /* > normI denotes the infinity norm of a matrix (maximum row sum) and */ /* > normF denotes the Frobenius norm of a matrix (square root of sum of */ /* > squares). Note that f2cmax(abs(A(i,j))) is not a consistent matrix norm. */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \param[in] NORM */ /* > \verbatim */ /* > NORM is CHARACTER*1 */ /* > Specifies the value to be returned in ZLANTP as described */ /* > above. */ /* > \endverbatim */ /* > */ /* > \param[in] UPLO */ /* > \verbatim */ /* > UPLO is CHARACTER*1 */ /* > Specifies whether the matrix A is upper or lower triangular. */ /* > = 'U': Upper triangular */ /* > = 'L': Lower triangular */ /* > \endverbatim */ /* > */ /* > \param[in] DIAG */ /* > \verbatim */ /* > DIAG is CHARACTER*1 */ /* > Specifies whether or not the matrix A is unit triangular. */ /* > = 'N': Non-unit triangular */ /* > = 'U': Unit triangular */ /* > \endverbatim */ /* > */ /* > \param[in] N */ /* > \verbatim */ /* > N is INTEGER */ /* > The order of the matrix A. N >= 0. When N = 0, ZLANTP is */ /* > set to zero. */ /* > \endverbatim */ /* > */ /* > \param[in] AP */ /* > \verbatim */ /* > AP is COMPLEX*16 array, dimension (N*(N+1)/2) */ /* > The upper or lower triangular matrix A, packed columnwise in */ /* > a linear array. The j-th column of A is stored in the array */ /* > AP as follows: */ /* > if UPLO = 'U', AP(i + (j-1)*j/2) = A(i,j) for 1<=i<=j; */ /* > if UPLO = 'L', AP(i + (j-1)*(2n-j)/2) = A(i,j) for j<=i<=n. */ /* > Note that when DIAG = 'U', the elements of the array AP */ /* > corresponding to the diagonal elements of the matrix A are */ /* > not referenced, but are assumed to be one. */ /* > \endverbatim */ /* > */ /* > \param[out] WORK */ /* > \verbatim */ /* > WORK is DOUBLE PRECISION array, dimension (MAX(1,LWORK)), */ /* > where LWORK >= N when NORM = 'I'; otherwise, WORK is not */ /* > referenced. */ /* > \endverbatim */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date December 2016 */ /* > \ingroup complex16OTHERauxiliary */ /* ===================================================================== */ doublereal zlantp_(char *norm, char *uplo, char *diag, integer *n, doublecomplex *ap, doublereal *work) { /* System generated locals */ integer i__1, i__2; doublereal ret_val; /* Local variables */ extern /* Subroutine */ int dcombssq_(doublereal *, doublereal *); integer i__, j, k; logical udiag; extern logical lsame_(char *, char *); doublereal value; extern logical disnan_(doublereal *); doublereal colssq[2]; extern /* Subroutine */ int zlassq_(integer *, doublecomplex *, integer *, doublereal *, doublereal *); doublereal sum, ssq[2]; /* -- LAPACK auxiliary routine (version 3.7.0) -- */ /* -- LAPACK is a software package provided by Univ. of Tennessee, -- */ /* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */ /* December 2016 */ /* ===================================================================== */ /* Parameter adjustments */ --work; --ap; /* Function Body */ if (*n == 0) { value = 0.; } else if (lsame_(norm, "M")) { /* Find f2cmax(abs(A(i,j))). */ k = 1; if (lsame_(diag, "U")) { value = 1.; if (lsame_(uplo, "U")) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = k + j - 2; for (i__ = k; i__ <= i__2; ++i__) { sum = z_abs(&ap[i__]); if (value < sum || disnan_(&sum)) { value = sum; } /* L10: */ } k += j; /* L20: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = k + *n - j; for (i__ = k + 1; i__ <= i__2; ++i__) { sum = z_abs(&ap[i__]); if (value < sum || disnan_(&sum)) { value = sum; } /* L30: */ } k = k + *n - j + 1; /* L40: */ } } } else { value = 0.; if (lsame_(uplo, "U")) { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = k + j - 1; for (i__ = k; i__ <= i__2; ++i__) { sum = z_abs(&ap[i__]); if (value < sum || disnan_(&sum)) { value = sum; } /* L50: */ } k += j; /* L60: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = k + *n - j; for (i__ = k; i__ <= i__2; ++i__) { sum = z_abs(&ap[i__]); if (value < sum || disnan_(&sum)) { value = sum; } /* L70: */ } k = k + *n - j + 1; /* L80: */ } } } } else if (lsame_(norm, "O") || *(unsigned char *) norm == '1') { /* Find norm1(A). */ value = 0.; k = 1; udiag = lsame_(diag, "U"); if (lsame_(uplo, "U")) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (udiag) { sum = 1.; i__2 = k + j - 2; for (i__ = k; i__ <= i__2; ++i__) { sum += z_abs(&ap[i__]); /* L90: */ } } else { sum = 0.; i__2 = k + j - 1; for (i__ = k; i__ <= i__2; ++i__) { sum += z_abs(&ap[i__]); /* L100: */ } } k += j; if (value < sum || disnan_(&sum)) { value = sum; } /* L110: */ } } else { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (udiag) { sum = 1.; i__2 = k + *n - j; for (i__ = k + 1; i__ <= i__2; ++i__) { sum += z_abs(&ap[i__]); /* L120: */ } } else { sum = 0.; i__2 = k + *n - j; for (i__ = k; i__ <= i__2; ++i__) { sum += z_abs(&ap[i__]); /* L130: */ } } k = k + *n - j + 1; if (value < sum || disnan_(&sum)) { value = sum; } /* L140: */ } } } else if (lsame_(norm, "I")) { /* Find normI(A). */ k = 1; if (lsame_(uplo, "U")) { if (lsame_(diag, "U")) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { work[i__] = 1.; /* L150: */ } i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { work[i__] += z_abs(&ap[k]); ++k; /* L160: */ } ++k; /* L170: */ } } else { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { work[i__] = 0.; /* L180: */ } i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = j; for (i__ = 1; i__ <= i__2; ++i__) { work[i__] += z_abs(&ap[k]); ++k; /* L190: */ } /* L200: */ } } } else { if (lsame_(diag, "U")) { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { work[i__] = 1.; /* L210: */ } i__1 = *n; for (j = 1; j <= i__1; ++j) { ++k; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { work[i__] += z_abs(&ap[k]); ++k; /* L220: */ } /* L230: */ } } else { i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { work[i__] = 0.; /* L240: */ } i__1 = *n; for (j = 1; j <= i__1; ++j) { i__2 = *n; for (i__ = j; i__ <= i__2; ++i__) { work[i__] += z_abs(&ap[k]); ++k; /* L250: */ } /* L260: */ } } } value = 0.; i__1 = *n; for (i__ = 1; i__ <= i__1; ++i__) { sum = work[i__]; if (value < sum || disnan_(&sum)) { value = sum; } /* L270: */ } } else if (lsame_(norm, "F") || lsame_(norm, "E")) { /* Find normF(A). */ /* SSQ(1) is scale */ /* SSQ(2) is sum-of-squares */ /* For better accuracy, sum each column separately. */ if (lsame_(uplo, "U")) { if (lsame_(diag, "U")) { ssq[0] = 1.; ssq[1] = (doublereal) (*n); k = 2; i__1 = *n; for (j = 2; j <= i__1; ++j) { colssq[0] = 0.; colssq[1] = 1.; i__2 = j - 1; zlassq_(&i__2, &ap[k], &c__1, colssq, &colssq[1]); dcombssq_(ssq, colssq); k += j; /* L280: */ } } else { ssq[0] = 0.; ssq[1] = 1.; k = 1; i__1 = *n; for (j = 1; j <= i__1; ++j) { colssq[0] = 0.; colssq[1] = 1.; zlassq_(&j, &ap[k], &c__1, colssq, &colssq[1]); dcombssq_(ssq, colssq); k += j; /* L290: */ } } } else { if (lsame_(diag, "U")) { ssq[0] = 1.; ssq[1] = (doublereal) (*n); k = 2; i__1 = *n - 1; for (j = 1; j <= i__1; ++j) { colssq[0] = 0.; colssq[1] = 1.; i__2 = *n - j; zlassq_(&i__2, &ap[k], &c__1, colssq, &colssq[1]); dcombssq_(ssq, colssq); k = k + *n - j + 1; /* L300: */ } } else { ssq[0] = 0.; ssq[1] = 1.; k = 1; i__1 = *n; for (j = 1; j <= i__1; ++j) { colssq[0] = 0.; colssq[1] = 1.; i__2 = *n - j + 1; zlassq_(&i__2, &ap[k], &c__1, colssq, &colssq[1]); dcombssq_(ssq, colssq); k = k + *n - j + 1; /* L310: */ } } } value = ssq[0] * sqrt(ssq[1]); } ret_val = value; return ret_val; /* End of ZLANTP */ } /* zlantp_ */
the_stack_data/2716.c
/* { dg-do run } */ /* { dg-require-effective-target size32plus } */ /* { dg-options "-fno-strict-volatile-bitfields" } */ extern void abort (void); #pragma pack(1) volatile struct S0 { signed a : 7; unsigned b : 28; /* b can't be fetched with an aligned 32-bit access, */ /* but it certainly can be fetched with an unaligned access */ } g = {0,0xfffffff}; int main() { unsigned b = g.b; if (b != 0xfffffff) abort (); return 0; }
the_stack_data/193893395.c
/* ************************************************************************** */ /* */ /* :::::::: */ /* ft_isascii.c :+: :+: */ /* +:+ */ /* By: mvan-eng <[email protected]> +#+ */ /* +#+ */ /* Created: 2019/01/14 19:36:06 by mvan-eng #+# #+# */ /* Updated: 2019/01/30 20:08:48 by mvan-eng ######## odam.nl */ /* */ /* ************************************************************************** */ int ft_isascii(int c) { if (c >= 0 && c <= 127) return (1); else return (0); }
the_stack_data/57950639.c
/* * scanf 用法三 * scanf(输入控制符 输入控制符,输入参数,输入参数) * * */ #include <stdio.h> int main(void) { int i, j; scanf("%d%d", &i, &j); printf("i=%d, j=%d", i, j); return 0; }
the_stack_data/29825243.c
extern const unsigned char Pods_checkFrameworkVersionString[]; extern const double Pods_checkFrameworkVersionNumber; const unsigned char Pods_checkFrameworkVersionString[] __attribute__ ((used)) = "@(#)PROGRAM:Pods_checkFramework PROJECT:Pods-1" "\n"; const double Pods_checkFrameworkVersionNumber __attribute__ ((used)) = (double)1.;
the_stack_data/792556.c
/* test case to illustrate how use-def can't be computed without points-to */ #include <stdio.h> int main() { int i[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int * q = &i[0]; int * p = &i[0]; // Increment i[0] (*q)++; // increment q int j = *q++; // The loaded value is not used printf("i=%d, p=%p, q=%p\n", i[0], p, q); return j; }
the_stack_data/12638121.c
#include <stdio.h> int main(){ double n = 0, i, x = 1; for(i = 1; i < 39; i+=2){ if(i == 1){ n+=1; }else{ x *= 2; n += (i/x); } } printf("%.2lf\n", n); return 0; }
the_stack_data/153028.c
#include <stdio.h> #include <string.h> int main() { char str[35]; while(scanf("%s", str) == 1) { if(!strcmp(str, "~")) break; int flag = 0, len; unsigned int ans = 0; do { len = strlen(str); if(len == 1) flag = 1; else if(len == 2) flag = 0; else { for(len -= 2; len > 0; len--) ans = (ans << 1) | flag; } } while(scanf("%s", str) == 1 && strcmp(str, "#")); printf("%u\n", ans); } }
the_stack_data/34513828.c
// RUN: %cml %s -o %t && %t | FileCheck %s #include <stdio.h> int main() { unsigned short k; k = 10; // CHECK: 10 printf("%u\n", k); return 0; }
the_stack_data/54825349.c
#include<stdio.h> #include<stdlib.h> #include<time.h> int main(){ srand(time(NULL)); int numero, sorte; sorte = rand() % 9; printf("Escolha um número entre 0 a 9: "); scanf("%d", &numero); if (numero < 0 || numero > 9){ printf("\n\nEu disse um numero entre 0 e 9\n\n"); }else{ if(numero == sorte){ printf("\n\n Você ACERTOU. numero sorteado: %d. \n\n"); }else{ printf("\n\n Você ERROU. numero sortado: %d \n\n",sorte); } } return 0; }
the_stack_data/755756.c
#include <inttypes.h> #include <stdio.h> #include <stdlib.h> const char arr[] = "hello"; const char *cp = arr; int main(int argc, char *argv[]) { printf("Size of arr %lu\n", (unsigned long)sizeof(arr)); printf("Size of *cp %lu\n", (unsigned long)sizeof(*cp)); exit(EXIT_SUCCESS); }
the_stack_data/107953524.c
#include<stdio.h> #include<math.h> int main() { int a,b; float c; for(a=1;a<=30;a++) { for(b=1;b<=30;b++) { c = sqrt(a*a+b*b); if(c == (int)c) { printf("%d + %d = %d\n",a,b,(int)c); } } } }
the_stack_data/951245.c
/******************************************************************************* * * Copyright (C) 2014-2018 Wave Computing, Inc. * * 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. * ******************************************************************************/ /* This file may have been modified by DJ Delorie (Jan 1991). If so, ** these modifications are Copyright (C) 1991 DJ Delorie. */ /* * Copyright (c) 1987 Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms are permitted * provided that: (1) source distributions retain this entire copyright * notice and comment, and (2) distributions including binaries display * the following acknowledgement: ``This product includes software * developed by the University of California, Berkeley and its contributors'' * in the documentation or other materials provided with the distribution * and in all advertising materials mentioning features or use of this * software. 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <stdlib.h> #include <stddef.h> #include <string.h> extern char **environ; /* Only deal with a pointer to environ, to work around subtle bugs with shared libraries and/or small data systems where the user declares his own 'environ'. */ static char ***p_environ = &environ; /* * findenv -- * Returns pointer to value associated with name, if any, else NULL. * Sets offset to be the offset of the name/value combination in the * environmental array, for use by setenv(3) and unsetenv(3). * * This routine *should* be a static; don't use it. */ char * __findenv (register const char *name, int *offset) { register int len; register char **p; const char *c; /* In some embedded systems, this does not get set. This protects newlib from dereferencing a bad pointer. */ if (!*p_environ) return NULL; c = name; while (*c && *c != '=') c++; /* Identifiers may not contain an '=', so cannot match if does */ if(*c != '=') { len = c - name; for (p = *p_environ; *p; ++p) if (!strncmp (*p, name, len)) if (*(c = *p + len) == '=') { *offset = p - *p_environ; return (char *) (++c); } } return NULL; }
the_stack_data/145451983.c
/* Example code for Exercises in C. This program shows a way to represent a BigInt type (arbitrary length integers) using C strings, with numbers represented as a string of decimal digits in reverse order. Follow these steps to get this program working: 1) Read through the whole program so you understand the design. 2) Compile and run the program. It should run three tests, and they should fail. 3) Fill in the body of reverse_string(). When you get it working, the first test should pass. 4) Fill in the body of itoc(). When you get it working, the second test should pass. 5) Fill in the body of add_digits(). When you get it working, the third test should pass. 6) Uncomment the last test in main. If your three previous tests pass, this one should, too. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <assert.h> /* reverse_string: Returns a new string with the characters reversed. It is the caller's responsibility to free the result. s: string returns: string */ char *reverse_string(char *s) { int s_len = strlen(s); char * temp = (char *) malloc(s_len); for (int i=0; i<s_len; i++) { temp[s_len-i-1] = s[i]; } return temp; } /* ctoi: Converts a character to integer. c: one of the characters '0' to '9' returns: integer 0 to 9 */ int ctoi(char c) { assert(isdigit(c)); return c - '0'; } /* itoc: Converts an integer to character. i: integer 0 to 9 returns: character '0' to '9' */ char itoc(int i) { //TODO: Fill this in, with an appropriate assertion. return '0' + i; } /* add_digits: Adds two decimal digits, returns the total and carry. For example, if a='5', b='6', and carry='1', the sum is 12, so the output value of total should be '2' and carry should be '1' a: character '0' to '9' b: character '0' to '9' c: character '0' to '9' total: pointer to char carry: pointer to char */ void add_digits(char a, char b, char c, char *total, char *carry) { int running_total = ctoi(a)+ctoi(b)+ctoi(c); *total = itoc(running_total % 10); *carry = itoc(running_total / 10); //TODO: Fill this in. } /* Define a type to represent a BigInt. Internally, a BigInt is a string of digits, with the digits in reverse order. */ typedef char * BigInt; /* add_bigint: Adds two BigInts Stores the result in z. x: BigInt y: BigInt carry_in: char z: empty buffer */ void add_bigint(BigInt x, BigInt y, char carry_in, BigInt z) { char total, carry_out; int dx=1, dy=1, dz=1; char a, b; /* OPTIONAL TODO: Modify this function to allocate and return z * rather than taking an empty buffer as a parameter. * Hint: you might need a helper function. */ if (*x == '\0') { a = '0'; dx = 0; }else{ a = *x; } if (*y == '\0') { b = '0'; dy = 0; }else{ b = *y; } // printf("%c %c %c\n", a, b, carry_in); add_digits(a, b, carry_in, &total, &carry_out); // printf("%c %c\n", carry_out, total); // if total and carry are 0, we're done if (total == '0' && carry_out == '0') { *z = '\0'; return; } // otherwise store the digit we just computed *z = total; // and make a recursive call to fill in the rest. add_bigint(x+dx, y+dy, carry_out, z+dz); } /* print_bigint: Prints the digits of BigInt in the normal order. big: BigInt */ void print_bigint(BigInt big) { char c = *big; if (c == '\0') return; print_bigint(big+1); printf("%c", c); } /* make_bigint: Creates and returns a BigInt. Caller is responsible for freeing. s: string of digits in the usual order returns: BigInt */ BigInt make_bigint(char *s) { char *r = reverse_string(s); return (BigInt) r; } void test_reverse_string() { char *s = "123"; char *t = reverse_string(s); if (strcmp(t, "321") == 0) { printf("reverse_string passed\n"); } else { printf("reverse_string failed\n"); } } void test_itoc() { char c = itoc(3); if (c == '3') { printf("itoc passed\n"); } else { printf("itoc failed\n"); } } void test_add_digits() { char total, carry; add_digits('7', '4', '1', &total, &carry); if (total == '2' && carry == '1') { printf("add_digits passed\n"); } else { printf("add_digits failed\n"); } } void test_add_bigint() { char *s = "1"; char *t = "99999999999999999999999999999999999999999999"; char *res = "000000000000000000000000000000000000000000001"; BigInt big1 = make_bigint(s); BigInt big2 = make_bigint(t); BigInt big3 = malloc(100); add_bigint(big1, big2, '0', big3); if (strcmp(big3, res) == 0) { printf("add_bigint passed\n"); } else { printf("add_bigint failed\n"); } } int main (int argc, char *argv[]) { test_reverse_string(); test_itoc(); test_add_digits(); //TODO: When you have the first three functions working, // uncomment the following, and it should work. test_add_bigint(); return 0; }
the_stack_data/63393.c
#include <stdio.h> int main() { return 0; } void PyInit_dummy() {}
the_stack_data/222405.c
void prebuilt_func_C(){}
the_stack_data/190769362.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #define BUFFSIZE 1024 #define PORT 8000 //declare global variables int sock_desc, ret; struct sockaddr_in server_addr; int client_sock; struct sockaddr_in client_addr; socklen_t addr_size; char buffer[BUFFSIZE]; pid_t childpid; char *login; int authenticateUser(char *login); void recieveClientFile(int client_sock); int main(){ int authResult = 0; // 2 - Create the socket sock_desc = socket(AF_INET, SOCK_STREAM, 0); if(sock_desc < 0){ printf("Error creating socket.\n"); exit(1); } printf("Server socket has been created.\n"); // 3 - Initialise the socket //memset(&server_addr, '\0', sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(PORT); server_addr.sin_addr.s_addr = INADDR_ANY; // 4 - Bind the socket if(bind(sock_desc, (struct sockaddr*)&server_addr, sizeof(server_addr)) < 0){ perror("Error binding server socket"); exit(1); } printf("Socket Binding to port %d successful\n", 8888); // 5 - Listen for client connections if(listen(sock_desc, 10) == 0){ printf("Waiting for client connections...\n"); }else{ printf("[-]Error in binding.\n"); } //infinite loop to continuously listen for connections while(1){ // 6 - Accept a clients connection client_sock = accept(sock_desc, (struct sockaddr*)&client_addr, &addr_size); if(client_sock < 0){ perror("Closing client connection..."); exit(1); } // print client details using inet_ntoa() and inet_ntohs() - converts from network byte order to string printf("Connection accepted from %s:%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port)); //create a new process for the client using fork() if((childpid = fork()) == 0){ close(sock_desc); //infinite loop to deal with client //for testing simply prints the clients message //exits when "exit" specified while(1){ printf("authenticaing user\n"); //read in the username memset(buffer, 0, BUFFSIZE); recv(client_sock, buffer, BUFFSIZE, 0); login = &buffer[0]; printf("login: %s\n", login); //AUTH USER authResult = authenticateUser(login); //authenticate the user if( authResult == 0){ printf("Unsuccessful login\n"); send(client_sock, "unsuccessful", strlen("unsuccessful"), 0); exit(1); }else{ send(client_sock, "successful", strlen("successful"), 0); //proceed with the file transfer recieveClientFile(client_sock); printf("File transfered successfully\n"); exit(1); } }//end while }//end fork() }//end listening while close(client_sock); return 0; }//end server //function to handle recieving files from client void recieveClientFile(int client_sock){ char file_buffer[512]; char* file_path = ""; //read in the destination memset(buffer, 0, BUFFSIZE); if(recv(client_sock, buffer, BUFFSIZE, 0) < 0){ //destination read error printf("destination of file cannot be read\n"); } printf("file destination: %s\n", buffer); file_path = buffer; FILE *file_open = fopen(file_path, "w"); if(file_open == NULL){ printf("File %s cannot be opened on server\n", file_path); } else{ bzero(file_buffer, 512); int block_size = 0, i=0; while((block_size = recv(client_sock, file_buffer, 512, 0)) > 0){ printf("Data Received %d = %d\n", i, block_size); int write_sz = fwrite(file_buffer, sizeof(char), block_size, file_open); bzero(file_buffer, 512); i++; } } printf("Transfer completed successfully\n"); fclose(file_open); } //function that authenitcates a username and password int authenticateUser(char *login){ char del[2] = ","; char *userDetails; char line[128]; FILE *file = fopen("users.txt", "r"); if(file){ while(fgets(line, sizeof(line), file)){ /* get the first token */ userDetails = strtok(line, del); if(strcmp(userDetails, login) == 0){ return 1; } } fclose(file); return 0; } }
the_stack_data/80945.c
/* Exercise 1 - Calculations Write a C program to input marks of two subjects. Calculate and print the average of the two marks. */ #include <stdio.h> int main() { int num1,num2; float AVG; printf("Enter Num1 = "); scanf("%d",&num1); printf("Enter Num2 = "); scanf("%d",&num2); AVG=(num1+num2)/2; printf("AVG Is = %.2f",AVG); return 0; }
the_stack_data/148579061.c
#include <stdio.h> #include <stdlib.h> int main() { float a, b, c; char op; scanf("%f%c%f", &a, &op, &b); switch(op) { case '+': c = a + b; break; case '-': c = a - b; break; case '*': c = a * b; break; case '/': c = a / b; break; default: printf("error"); exit(0); } printf("result=%.2f", c); return 0; }
the_stack_data/73576596.c
#include <stdbool.h> #include <stdio.h> bool is_num(char c) { return c >= '0' && c <= '9'; } char read_num(int *a) { int cur = 0; while (1) { char c; scanf("%c", &c); if (is_num(c)) { cur = cur * 10 + c - '0'; } else { *a = cur; return c; } } } int main() { int ans = 0; while (1) { int a, b; char sep = read_num(&a); if (sep == '-') { read_num(&b); ans += b - a + 1; } else if (a != 0) { ans++; } else { break; } } printf("%d", ans); return 0; }
the_stack_data/234517761.c
/*Exercise 3 - Repetition Write a C program to calculate the sum of the numbers from 1 to n. Where n is a keyboard input. e.g. n -> 100 sum = 1+2+3+....+ 99+100 = 5050 n -> 1- sum = 1+2+3+...+10 = 55 */ #include <stdio.h> int main() { int x=1; int num; int total=0; printf("Enter the number:"); scanf("%d",&num); while(x <= num){ total += x; x++; } printf("Sum : %d",total); return 0; }
the_stack_data/580754.c
#include <stdio.h> /* Find bug with call 'valgrind --track-origins=yes -q ./valgrind_test5' */ int main(void) { int flag; /* BUG: variable in condition is not initialized */ if (flag) { printf("Flag was not 0\n"); } else { printf("Flag was 0\n"); } return 0; }
the_stack_data/145452613.c
#include <stdio.h> void trocar(int *a, int *b) { int t = *a; *a = *b; *b = t; } void bubbleSort(int vet[], int t) { int memoria, troca = 1; for (int i = t - 1; i >= 1 && troca == 1; --i) { troca = 0; for (int j = 0; j < i; ++j) if (vet[j] > vet[j + 1]) { trocar(&vet[j], &vet[j + 1]); troca = 1; } } } void exibir(int vet[], int t) { for (int i = 0; i < t; ++i) printf(" %d", vet[i]); printf("\n"); } int main(void) { int vet[] = {61, 51, 6, 50, 78, 40, 87, 88, 36, 7, 9, 53, 2, 9, 25}; int tam = sizeof(vet) / sizeof(vet[0]); exibir(vet, tam); bubbleSort(vet, tam); exibir(vet, tam); return 0; }
the_stack_data/122014947.c
/*** links ***/ // https://viewsourcecode.org/snaptoken/kilo/02.enteringRawMode.html // https://viewsourcecode.org/snaptoken/kilo/03.rawInputAndOutput.html // https://viewsourcecode.org/snaptoken/kilo/04.aTextViewer.html // https://viewsourcecode.org/snaptoken/kilo/05.aTextEditor.html /*** includes ***/ // Step 59 - feature test macro // https://www.gnu.org/software/libc/manual/html_node/Feature-Test-Macros.html #define _DEFAULT_SOURCE #define _BSD_SOURCE #define _GNU_SOURCE #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <sys/ioctl.h> #include <sys/types.h> #include <termios.h> #include <time.h> #include <unistd.h> /*** defines ***/ // Step 41 #define KILO_VERSION "0.0.1" #define KILO_TAB_STOP 8 // The CTRL_KEY macro bitwise-ANDs a character with the value 00011111, in // binary. (In C, you generally specify bitmasks using hexadecimal, since C // doesn’t have binary literals, and hexadecimal is more concise and readable // once you get used to it.) In other words, it sets the upper 3 bits of the // character to 0. This mirrors what the Ctrl key does in the terminal: it // strips bits 5 and 6 from whatever key you press in combination with Ctrl, and // sends that. (By convention, bit numbering starts from 0.) The ASCII character // set seems to be designed this way on purpose. (It is also similarly designed // so that you can set and clear bit 5 to switch between lowercase and // uppercase.) #define CTRL_KEY(k) ((k)&0x1f) enum editorKey { BACKSPACE = 127, ARROW_LEFT = 1000, ARROW_RIGHT, ARROW_UP, ARROW_DOWN, DEL_KEY, HOME_KEY, END_KEY, PAGE_UP, PAGE_DOWN }; /*** data ***/ // erow stands for “editor row”, and stores a line // of text as a pointer to the dynamically-allocated // character data and a length. // The typedef lets us refer to the type as erow // instead of struct erow. typedef struct erow { int size; int rsize; char *chars; char *render; } erow; struct editorConfig { int cx, cy; int rx; int rowoff; int coloff; int screenrows; int screencols; int numrows; erow *row; char *filename; char statusmsg[80]; time_t statusmsg_time; struct termios orig_termios; }; struct editorConfig E; /*** terminal ***/ void die(const char *s) { write(STDOUT_FILENO, "\x1b[2J", 4); write(STDOUT_FILENO, "\x1b[H", 3); perror(s); exit(1); } void disableRawMode() { if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &E.orig_termios) == -1) die("tcsetattr"); // printf("Quitting after disabling raw mode!\n"); } void enableRawMode() { if (tcgetattr(STDIN_FILENO, &E.orig_termios) == -1) die("tcgetattr"); // We use it to register our disableRawMode() function to be called // automatically when the program exits, whether it exits by returning from // main(), or by calling the exit() function atexit(disableRawMode); struct termios raw = E.orig_termios; // ECHO is a bitflag, defined as 00000000000000000000000000001000 in binary. // We use the bitwise-NOT operator (~) on this value to get // 11111111111111111111111111110111. We then bitwise-AND this value with the // flags field, which forces the fourth bit in the flags field to become 0, // and causes every other bit to retain its current value. Flipping bits like // this is common in C. // Step 7 // There is an ICANON flag that allows us to turn off canonical mode. This // means we will finally be reading input byte-by-byte, instead of // line-by-line. // Step 9 // Disable Ctrl-C and Ctrl-Z using ISIG // Step 10 // Disable Ctrl-S and Ctrl-Q // They are read as 19 and 17 respectively // Step 11 // Disable Ctrl-V and Ctrl-O // Step 12 // Disable Ctrl-M and Ctrl-J // They are read as 13 and 10 respectively // Step 15 - turn off more flags raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); // Step 15 raw.c_cflag |= (CS8); raw.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); // Step 13 // turnoff output processing // turnoff POST processing of outputs // From now on, we’ll have to write out the full "\r\n" whenever we want to // start a new line. raw.c_oflag = ~(OPOST); // Step 16 raw.c_cc[VMIN] = 0; raw.c_cc[VTIME] = 1; // Step 18 - testing // An easy way to make tcgetattr() fail is to // give your program a text file or a pipe as // the standard input instead of your terminal. // To give it a file as standard input, // run ./kilo <kilo.c. To give it a pipe, // run echo test | ./kilo. Both should result // in the same error from tcgetattr(), // something like Inappropriate ioctl for device. if (tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw) == -1) die("tcsetattr"); } // editorReadKey()’s job is to wait for one keypress, and return it. Later, // we’ll expand this function to handle escape sequences, which involves reading // multiple bytes that represent a single keypress, as is the case with the // arrow keys. int editorReadKey() { int nread; char c; while ((nread = read(STDIN_FILENO, &c, 1)) != 1) { if (nread == -1 && errno != EAGAIN) die("read"); } if (c == '\x1b') { char seq[3]; if (read(STDIN_FILENO, &seq[0], 1) != 1) return '\x1b'; if (read(STDIN_FILENO, &seq[1], 1) != 1) return '\x1b'; if (seq[0] == '[') { if (seq[1] >= '0' && seq[1] <= '9') { if (read(STDIN_FILENO, &seq[2], 1) != 1) return '\x1b'; if (seq[2] == '~') { switch (seq[1]) { case '1': return HOME_KEY; case '3': return DEL_KEY; case '4': return END_KEY; case '5': return PAGE_UP; case '6': return PAGE_DOWN; case '7': return HOME_KEY; case '8': return END_KEY; } } } else { switch (seq[1]) { case 'A': return ARROW_UP; case 'B': return ARROW_DOWN; case 'C': return ARROW_RIGHT; case 'D': return ARROW_LEFT; case 'H': return HOME_KEY; case 'F': return END_KEY; } } } else if (seq[0] == 'O') { switch (seq[1]) { case 'H': return HOME_KEY; case 'F': return END_KEY; } } return '\x1b'; } else { return c; } } int getCursorPosition(int *rows, int *cols) { char buf[32]; unsigned int i = 0; if (write(STDOUT_FILENO, "\x1b[6n", 4) != 4) return -1; while (i < sizeof(buf) - 1) { if (read(STDIN_FILENO, &buf[i], 1) != 1) break; if (buf[i] == 'R') break; i++; } buf[i] = '\0'; if (buf[0] != '\x1b' || buf[1] != '[') return -1; if (sscanf(&buf[2], "%d;%d", rows, cols) != 2) return -1; return 0; } int getWindowSize(int *rows, int *cols) { struct winsize ws; if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0) { // As you might have gathered from the code, there is no simple “move the // cursor to the bottom-right corner” command. if (write(STDOUT_FILENO, "\x1b[999C\x1b[999B", 12) != 12) return -1; return getCursorPosition(rows, cols); } else { *cols = ws.ws_col; *rows = ws.ws_row; return 0; } } /*** row operations ***/ int editorRowCxToRx(erow *row, int cx) { int rx = 0; int j; for (j = 0; j < cx; j++) { if (row->chars[j] == '\t') rx += (KILO_TAB_STOP - 1) - (rx % KILO_TAB_STOP); rx++; } return rx; } void editorUpdateRow(erow *row) { int tabs = 0; int j; for (j = 0; j < row->size; j++) if (row->chars[j] == '\t') tabs++; free(row->render); row->render = malloc(row->size + tabs*(KILO_TAB_STOP - 1) + 1); int idx = 0; for (j = 0; j < row->size; j++) { if (row->chars[j] == '\t') { row->render[idx++] = ' '; while( idx % KILO_TAB_STOP != 0) row->render[idx++] = ' '; } else { row-> render[idx++] = row->chars[j]; } } row->render[idx] = '\0'; row->rsize = idx; } void editorAppendRow(char *s, size_t len) { E.row = realloc(E.row, sizeof(erow) * (E.numrows + 1)); int at = E.numrows; E.row[at].size = len; E.row[at].chars = malloc(len + 1); memcpy(E.row[at].chars, s, len); E.row[at].chars[len] = '\0'; E.row[at].rsize = 0; E.row[at].render = NULL; editorUpdateRow(&E.row[at]); E.numrows++; } void editorRowInsertChar(erow *row, int at, int c) { if (at < 0 || at > row->size) at = row->size; row->chars = realloc(row->chars, row->size + 2); memmove(&row->chars[at + 1], &row->chars[at], row->size - at + 1); row->size++; row->chars[at] = c; editorUpdateRow(row); } /*** editor operations ***/ void editorInsertChar(int c) { if (E.cy == E.numrows) { editorAppendRow("", 0); } editorRowInsertChar(&E.row[E.cy], E.cx, c); E.cx++; } /*** file i/o ***/ // Step 105 // a function that converts our array of erow // structs into a single string that is ready // to be written out to a file. char *editorRowsToString(int *buflen) { int totlen = 0; int j; for (j = 0; j < E.numrows; j++) totlen += E.row[j].size + 1; *buflen = totlen; char *buf = malloc(totlen); char *p = buf; for (j = 0; j < E.numrows; j++) { memcpy(p, E.row[j].chars, E.row[j].size); p += E.row[j].size; *p = '\n'; p++; } return buf; } void editorOpen(char *filename) { free(E.filename); E.filename = strdup(filename); FILE *fp = fopen(filename, "r"); if (!fp) die("fopen"); char *line = NULL; size_t linecap = 0; ssize_t linelen; // Step 65 - read in the whole file while ((linelen = getline(&line, &linecap, fp)) != -1) { while (linelen >0 && (line[linelen-1] == '\n' || line[linelen-1] == '\r')) linelen--; editorAppendRow(line, linelen); } free(line); fclose(fp); } void editorSave() { if (E.filename == NULL) return; int len; char *buf = editorRowsToString(&len); int fd = open(E.filename, O_RDWR | O_CREAT, 0644); ftruncate(fd, len); write(fd, buf, len); close(fd); free(buf); } /*** append buffer ***/ // Step 36 - declaring a buffer struct abuf { char *b; int len; }; #define ABUF_INIT {NULL, 0} // initializer for a buffer void abAppend(struct abuf *ab, const char *s, int len) { char *new = realloc(ab->b, ab->len + len); if (new == NULL) return; memcpy(&new[ab->len], s, len); ab->b = new; ab->len += len; } void abFree(struct abuf *ab) { free(ab->b); } /*** output ***/ // Step 68 void editorScroll() { E.rx = 0; // Step 89 if (E.cy < E.numrows) { E.rx = editorRowCxToRx(&E.row[E.cy], E.cx); } if (E.cy < E.rowoff) { E.rowoff = E.cy; } if (E.cy >= E.rowoff + E.screenrows) { E.rowoff = E.cy - E.screenrows + 1; } // Step 73 // Exact parallel to vertical scrolling mode // E.cx <= E.cy // E.rowoff <= E.coloff // E.screenrows <= E.screencols // Step 86 if (E.rx < E.coloff) { E.coloff = E.rx; } if (E.rx >= E.coloff + E.screencols) { E.coloff = E.rx - E.screencols + 1; } } // editorDrawRows() will handle drawing each row of the buffer of text being // edited. For now it draws a tilde in each row, which means that row is not // part of the file and can’t contain any text. void editorDrawRows(struct abuf *ab) { int y; for (y = 0; y < E.screenrows; y++) { int filerow = y + E.rowoff; if (filerow >= E.numrows) { // Step 60 if (E.numrows == 0 && y == E.screenrows / 3) { // Step 41 char welcome[80]; int welcomelen = snprintf(welcome, sizeof(welcome), "Kilo editor -- version %s", KILO_VERSION); if (welcomelen > E.screencols) welcomelen = E.screencols; // Step 42 - centering int padding = (E.screencols - welcomelen) / 2; if (padding) { abAppend(ab, "~", 1); padding--; } while (padding--) abAppend(ab, " ", 1); abAppend(ab, welcome, welcomelen); } else { abAppend(ab, "~", 1); } } else { int len = E.row[filerow].rsize - E.coloff; if (len < 0) len = 0; if (len > E.screencols) len = E.screencols; abAppend(ab, &E.row[filerow].render[E.coloff], len); } // Step 40 one at a time abAppend(ab, "\x1b[K", 3); // Step 92 - room for status bar abAppend(ab, "\r\n", 2); } } void editorDrawStatusBar(struct abuf *ab) { abAppend(ab, "\x1b[7m", 4); char status[80], rstatus[80]; int len = snprintf(status, sizeof(status), "%.20s - %d lines", E.filename ? E.filename : "[No Name]", E.numrows); int rlen = snprintf(rstatus, sizeof(rstatus), "%d%d", E.cy + 1, E.numrows); if (len > E.screencols) len = E.screencols; abAppend(ab, status, len); while (len < E.screencols) { if (E.screencols - len == rlen) { abAppend(ab, rstatus, rlen); break; } else { abAppend(ab, " ", 1); len++; } } abAppend(ab, "\x1b[m", 3); abAppend(ab, "\r\n", 2); } void editorDrawMessageBar(struct abuf *ab) { abAppend(ab, "\x1b[K", 3); int msglen = strlen(E.statusmsg); if (msglen > E.screencols) msglen = E.screencols; if (msglen && time(NULL) - E.statusmsg_time < 5) abAppend(ab, E.statusmsg, msglen); } // The 4 in our write() call means we are writing 4 bytes out to the terminal. // The first byte is \x1b, which is the escape character, or 27 in decimal. (Try // and remember \x1b, we will be using it a lot.) The other three bytes are [2J. // // We are writing an escape sequence to the terminal. Escape sequences always // start with an escape character (27) followed by a [ character. Escape // sequences instruct the terminal to do various text formatting tasks, such as // coloring text, moving the cursor around, and clearing parts of the screen. // // We are using the J command (Erase In Display) to clear the screen. Escape // sequence commands take arguments, which come before the command. In this case // the argument is 2, which says to clear the entire screen. <esc>[1J would // clear the screen up to where the cursor is, and <esc>[0J would clear the // screen from the cursor up to the end of the screen. Also, 0 is the default // argument for J, so just <esc>[J by itself would also clear the screen from // the cursor to the end. void editorRefreshScreen() { editorScroll(); struct abuf ab = ABUF_INIT; abAppend(&ab, "\x1b[?25l", 6); abAppend(&ab, "\x1b[H", 3); editorDrawRows(&ab); editorDrawStatusBar(&ab); editorDrawMessageBar(&ab); // Step 44 char buf[32]; // Step 70 - to fix cursor scrolling on the screen //snprintf(buf, sizeof(buf), "\x1b[%d;%dH", E.cy + 1, E.cx + 1); snprintf(buf, sizeof(buf), "\x1b[%d;%dH", (E.cy - E.rowoff) + 1, (E.rx - E.coloff) + 1); abAppend(&ab, buf, strlen(buf)); abAppend(&ab, "\x1b[?25h", 6); write(STDOUT_FILENO, ab.b, ab.len); abFree(&ab); } void editorSetStatusMessage(const char *fmt, ...) { va_list ap; va_start(ap, fmt); vsnprintf(E.statusmsg, sizeof(E.statusmsg), fmt, ap); va_end(ap); E.statusmsg_time = time(NULL); } /*** input ***/ void editorMoveCursor(int key) { erow *row = (E.cy >= E.numrows) ? NULL : &E.row[E.cy]; switch (key) { case ARROW_LEFT: case 'h': if (E.cx != 0) { E.cx--; } else if (E.cy > 0) { E.cy--; E.cx = E.row[E.cy].size; } break; case ARROW_RIGHT: case 'l': // Step 74 - allow user to go pass the right edge of screen // and should be able to confirm horizontal scrolling works! //if (E.cx != E.screencols - 1) // Step 76 if (row && E.cx < row->size) { E.cx++; } else if (row && E.cx == row->size) { E.cy++; E.cx = 0; } break; case ARROW_UP: case 'k': if (E.cy != 0) E.cy--; break; case ARROW_DOWN: case 'j': // Step 69 - advance past bottom of screen but not file if (E.cy < E.numrows) E.cy++; //if (E.cy != E.screenrows-1) E.cy++; // Step 77 break; } row = (E.cy >= E.numrows)? NULL : &E.row[E.cy]; int rowlen = row ? row->size : 0; if (E.cx > rowlen) E.cx = rowlen; } // editorProcessKeypress() waits for a keypress, and then handles it. Later, it // will map various Ctrl key combinations and other special keys to different // editor functions, and insert any alphanumeric and other printable keys’ // characters into the text that is being edited. void editorProcessKeypress() { int c = editorReadKey(); switch (c) { case '\r': /* TODO */ break; case CTRL_KEY('q'): write(STDOUT_FILENO, "\x1b[2J", 4); write(STDOUT_FILENO, "\x1b[H", 3); exit(0); break; case CTRL_KEY('s'): editorSave(); break; case HOME_KEY: E.cx = 0; break; case END_KEY: // Step 91 if (E.cy < E.numrows) E.cx = E.row[E.cy].size; break; case BACKSPACE: case CTRL_KEY('h'): case DEL_KEY: /* TODO */ break; case PAGE_UP: case PAGE_DOWN: { if (c == PAGE_UP) { E.cy = E.rowoff; } else if (c == PAGE_DOWN) { E.cy = E.rowoff + E.screenrows - 1; if (E.cy > E.numrows) E.cy = E.numrows; } int times = E.screenrows; while (times--) editorMoveCursor(c == PAGE_UP? ARROW_UP : ARROW_DOWN); } break; case ARROW_UP: case ARROW_DOWN: case ARROW_LEFT: case ARROW_RIGHT: /*case 'j': case 'k': case 'l': case 'h':*/ editorMoveCursor(c); break; case CTRL_KEY('l'): case '\x1b': break; default: editorInsertChar(c); break; } } /*** init ***/ void initEditor() { // Step 43 E.cx = 0; E.cy = 0; E.rx = 0; E.rowoff = 0; E.coloff = 0; E.numrows = 0; E.row = NULL; E.filename = NULL; E.statusmsg[0] = '\0'; E.statusmsg_time = 0; if (getWindowSize(&E.screenrows, &E.screencols) == -1) die("getWindowSize"); E.screenrows -= 2; } int main(int argc, char *argv[]) { enableRawMode(); initEditor(); if (argc >= 2) editorOpen(argv[1]); editorSetStatusMessage("HELP: Ctrl-Q = quit"); while (1) { editorRefreshScreen(); editorProcessKeypress(); } return 0; }
the_stack_data/101078.c
#include <stdio.h> #include<string.h> //https://bowbowbow.tistory.com/6 char In[10000]; char Str[10000]; int Inlen, Strlen; int Pi[10000]; int findpi(){ int i; return 0; } int main(){ int i; scanf("%s",In); scanf("%s",Str); Inlen=strlen(In); Strlen=strlen(Str); findpi(); return 0; }
the_stack_data/686877.c
/**/ #include <stdio.h> int main() { int test, remainder, status, n; printf("\nEnter an integer > "); scanf("%d", &n); status = n; test = status; printf("\n"); if(n < 0) n = n * -1; while(test != 0) { remainder = n % 10; n = n / 10; test = n; if((status<0) && (n == 0)) remainder = -1 * remainder; printf("%d\n", remainder); } printf("That's all, have a nice day!\n"); return 0; }
the_stack_data/707706.c
#include <stdio.h> #include <stdlib.h> #include <time.h> void fib2rec(size_t n, size_t buf[2]) { if(n > 2) { size_t res = buf[0] + buf[1]; buf[1] = buf[0]; buf[0] = res; fib2rec(n - 1, buf); } } size_t fib2(size_t n) { size_t res[2] = {1, 1}; fib2rec(n, res); return res[0]; } int main(int argc, char const *argv[]) { size_t param = strtoul(argv[1], NULL, 10); printf("Provided limit: %zu\n", param); printf("Recursion starts\n\n"); clock_t start = clock(); printf("%zu\n", fib2(param)); clock_t end = clock(); float diff = (float)(end - start) / CLOCKS_PER_SEC; printf("Time taken : %fs\n", diff); return 0; }
the_stack_data/560212.c
#ifdef FR_VM #include "fni_ext.h" void sys_Obj_trap_v(fr_Env env, void *param, void *ret); void sys_Obj_isImmutable_v(fr_Env env, void *param, void *ret); void sys_Int_fromStr_v(fr_Env env, void *param, void *ret); void sys_Int_random_v(fr_Env env, void *param, void *ret); void sys_Int_privateMake_v(fr_Env env, void *param, void *ret); void sys_Int_equals_v(fr_Env env, void *param, void *ret); void sys_Int_compare_v(fr_Env env, void *param, void *ret); void sys_Int_negate_v(fr_Env env, void *param, void *ret); void sys_Int_increment_v(fr_Env env, void *param, void *ret); void sys_Int_decrement_v(fr_Env env, void *param, void *ret); void sys_Int_mult_v(fr_Env env, void *param, void *ret); void sys_Int_multFloat_v(fr_Env env, void *param, void *ret); void sys_Int_div_v(fr_Env env, void *param, void *ret); void sys_Int_divFloat_v(fr_Env env, void *param, void *ret); void sys_Int_mod_v(fr_Env env, void *param, void *ret); void sys_Int_modFloat_v(fr_Env env, void *param, void *ret); void sys_Int_plus_v(fr_Env env, void *param, void *ret); void sys_Int_plusFloat_v(fr_Env env, void *param, void *ret); void sys_Int_minus_v(fr_Env env, void *param, void *ret); void sys_Int_minusFloat_v(fr_Env env, void *param, void *ret); void sys_Int_not__v(fr_Env env, void *param, void *ret); void sys_Int_and__v(fr_Env env, void *param, void *ret); void sys_Int_or__v(fr_Env env, void *param, void *ret); void sys_Int_xor__v(fr_Env env, void *param, void *ret); void sys_Int_shiftl_v(fr_Env env, void *param, void *ret); void sys_Int_shiftr_v(fr_Env env, void *param, void *ret); void sys_Int_shifta_v(fr_Env env, void *param, void *ret); void sys_Int_pow_v(fr_Env env, void *param, void *ret); void sys_Int_toStr_v(fr_Env env, void *param, void *ret); void sys_Int_toHex_v(fr_Env env, void *param, void *ret); void sys_Int_toRadix_v(fr_Env env, void *param, void *ret); void sys_Int_toChar_v(fr_Env env, void *param, void *ret); void sys_Int_toCode_v(fr_Env env, void *param, void *ret); void sys_Int_toFloat_v(fr_Env env, void *param, void *ret); void sys_Func_call_v(fr_Env env, void *param, void *ret); void sys_Func_call__0_v(fr_Env env, void *param, void *ret); void sys_Func_call__1_v(fr_Env env, void *param, void *ret); void sys_Func_call__2_v(fr_Env env, void *param, void *ret); void sys_Func_call__3_v(fr_Env env, void *param, void *ret); void sys_Func_call__4_v(fr_Env env, void *param, void *ret); void sys_Func_call__5_v(fr_Env env, void *param, void *ret); void sys_Func_call__6_v(fr_Env env, void *param, void *ret); void sys_Func_call__7_v(fr_Env env, void *param, void *ret); void sys_BindFunc_call_v(fr_Env env, void *param, void *ret); void sys_BindFunc_call__0_v(fr_Env env, void *param, void *ret); void sys_BindFunc_call__1_v(fr_Env env, void *param, void *ret); void sys_BindFunc_call__2_v(fr_Env env, void *param, void *ret); void sys_BindFunc_call__3_v(fr_Env env, void *param, void *ret); void sys_BindFunc_call__4_v(fr_Env env, void *param, void *ret); void sys_BindFunc_call__5_v(fr_Env env, void *param, void *ret); void sys_BindFunc_call__6_v(fr_Env env, void *param, void *ret); void sys_BindFunc_call__7_v(fr_Env env, void *param, void *ret); void sys_Str_intern_v(fr_Env env, void *param, void *ret); void sys_Str_format_v(fr_Env env, void *param, void *ret); void sys_Bool_equals_v(fr_Env env, void *param, void *ret); void sys_Bool_not__v(fr_Env env, void *param, void *ret); void sys_Bool_and__v(fr_Env env, void *param, void *ret); void sys_Bool_or__v(fr_Env env, void *param, void *ret); void sys_Bool_xor__v(fr_Env env, void *param, void *ret); void sys_Ptr_make_v(fr_Env env, void *param, void *ret); void sys_Ptr_stackAlloc_v(fr_Env env, void *param, void *ret); void sys_Ptr_load_v(fr_Env env, void *param, void *ret); void sys_Ptr_store_v(fr_Env env, void *param, void *ret); void sys_Ptr_plus_v(fr_Env env, void *param, void *ret); void sys_Ptr_set_v(fr_Env env, void *param, void *ret); void sys_Ptr_get_v(fr_Env env, void *param, void *ret); void sys_Array_make_v(fr_Env env, void *param, void *ret); void sys_Array_size_v(fr_Env env, void *param, void *ret); void sys_Array_get_v(fr_Env env, void *param, void *ret); void sys_Array_set_v(fr_Env env, void *param, void *ret); void sys_Array_realloc_v(fr_Env env, void *param, void *ret); void sys_Array_arraycopy_v(fr_Env env, void *param, void *ret); void sys_Array_finalize_v(fr_Env env, void *param, void *ret); void sys_NativeC_toId_v(fr_Env env, void *param, void *ret); void sys_NativeC_typeName_v(fr_Env env, void *param, void *ret); void sys_NativeC_print_v(fr_Env env, void *param, void *ret); void sys_NativeC_printErr_v(fr_Env env, void *param, void *ret); void sys_NativeC_stackTrace_v(fr_Env env, void *param, void *ret); void sys_Float_makeBits_v(fr_Env env, void *param, void *ret); void sys_Float_makeBits32_v(fr_Env env, void *param, void *ret); void sys_Float_fromStr_v(fr_Env env, void *param, void *ret); void sys_Float_random_v(fr_Env env, void *param, void *ret); void sys_Float_equals_v(fr_Env env, void *param, void *ret); void sys_Float_isNaN_v(fr_Env env, void *param, void *ret); void sys_Float_negate_v(fr_Env env, void *param, void *ret); void sys_Float_mult_v(fr_Env env, void *param, void *ret); void sys_Float_multInt_v(fr_Env env, void *param, void *ret); void sys_Float_div_v(fr_Env env, void *param, void *ret); void sys_Float_divInt_v(fr_Env env, void *param, void *ret); void sys_Float_mod_v(fr_Env env, void *param, void *ret); void sys_Float_modInt_v(fr_Env env, void *param, void *ret); void sys_Float_plus_v(fr_Env env, void *param, void *ret); void sys_Float_plusInt_v(fr_Env env, void *param, void *ret); void sys_Float_minus_v(fr_Env env, void *param, void *ret); void sys_Float_minusInt_v(fr_Env env, void *param, void *ret); void sys_Float_bits_v(fr_Env env, void *param, void *ret); void sys_Float_bits32_v(fr_Env env, void *param, void *ret); void sys_Float_toStr_v(fr_Env env, void *param, void *ret); void sys_Float_toInt_v(fr_Env env, void *param, void *ret); void sys_Float_toLocale_v(fr_Env env, void *param, void *ret); void sys_Enum_doFromStr_v(fr_Env env, void *param, void *ret); void sys_register(fr_Fvm vm) { fr_registerMethod(vm, "sys_Obj_trap", sys_Obj_trap_v); fr_registerMethod(vm, "sys_Obj_isImmutable", sys_Obj_isImmutable_v); fr_registerMethod(vm, "sys_Int_fromStr", sys_Int_fromStr_v); fr_registerMethod(vm, "sys_Int_random", sys_Int_random_v); fr_registerMethod(vm, "sys_Int_privateMake", sys_Int_privateMake_v); fr_registerMethod(vm, "sys_Int_equals", sys_Int_equals_v); fr_registerMethod(vm, "sys_Int_compare", sys_Int_compare_v); fr_registerMethod(vm, "sys_Int_negate", sys_Int_negate_v); fr_registerMethod(vm, "sys_Int_increment", sys_Int_increment_v); fr_registerMethod(vm, "sys_Int_decrement", sys_Int_decrement_v); fr_registerMethod(vm, "sys_Int_mult", sys_Int_mult_v); fr_registerMethod(vm, "sys_Int_multFloat", sys_Int_multFloat_v); fr_registerMethod(vm, "sys_Int_div", sys_Int_div_v); fr_registerMethod(vm, "sys_Int_divFloat", sys_Int_divFloat_v); fr_registerMethod(vm, "sys_Int_mod", sys_Int_mod_v); fr_registerMethod(vm, "sys_Int_modFloat", sys_Int_modFloat_v); fr_registerMethod(vm, "sys_Int_plus", sys_Int_plus_v); fr_registerMethod(vm, "sys_Int_plusFloat", sys_Int_plusFloat_v); fr_registerMethod(vm, "sys_Int_minus", sys_Int_minus_v); fr_registerMethod(vm, "sys_Int_minusFloat", sys_Int_minusFloat_v); fr_registerMethod(vm, "sys_Int_not", sys_Int_not__v); fr_registerMethod(vm, "sys_Int_and", sys_Int_and__v); fr_registerMethod(vm, "sys_Int_or", sys_Int_or__v); fr_registerMethod(vm, "sys_Int_xor", sys_Int_xor__v); fr_registerMethod(vm, "sys_Int_shiftl", sys_Int_shiftl_v); fr_registerMethod(vm, "sys_Int_shiftr", sys_Int_shiftr_v); fr_registerMethod(vm, "sys_Int_shifta", sys_Int_shifta_v); fr_registerMethod(vm, "sys_Int_pow", sys_Int_pow_v); fr_registerMethod(vm, "sys_Int_toStr", sys_Int_toStr_v); fr_registerMethod(vm, "sys_Int_toHex", sys_Int_toHex_v); fr_registerMethod(vm, "sys_Int_toRadix", sys_Int_toRadix_v); fr_registerMethod(vm, "sys_Int_toChar", sys_Int_toChar_v); fr_registerMethod(vm, "sys_Int_toCode", sys_Int_toCode_v); fr_registerMethod(vm, "sys_Int_toFloat", sys_Int_toFloat_v); fr_registerMethod(vm, "sys_Func_call", sys_Func_call_v); fr_registerMethod(vm, "sys_Func_call$0", sys_Func_call__0_v); fr_registerMethod(vm, "sys_Func_call$1", sys_Func_call__1_v); fr_registerMethod(vm, "sys_Func_call$2", sys_Func_call__2_v); fr_registerMethod(vm, "sys_Func_call$3", sys_Func_call__3_v); fr_registerMethod(vm, "sys_Func_call$4", sys_Func_call__4_v); fr_registerMethod(vm, "sys_Func_call$5", sys_Func_call__5_v); fr_registerMethod(vm, "sys_Func_call$6", sys_Func_call__6_v); fr_registerMethod(vm, "sys_Func_call$7", sys_Func_call__7_v); fr_registerMethod(vm, "sys_BindFunc_call", sys_BindFunc_call_v); fr_registerMethod(vm, "sys_BindFunc_call$0", sys_BindFunc_call__0_v); fr_registerMethod(vm, "sys_BindFunc_call$1", sys_BindFunc_call__1_v); fr_registerMethod(vm, "sys_BindFunc_call$2", sys_BindFunc_call__2_v); fr_registerMethod(vm, "sys_BindFunc_call$3", sys_BindFunc_call__3_v); fr_registerMethod(vm, "sys_BindFunc_call$4", sys_BindFunc_call__4_v); fr_registerMethod(vm, "sys_BindFunc_call$5", sys_BindFunc_call__5_v); fr_registerMethod(vm, "sys_BindFunc_call$6", sys_BindFunc_call__6_v); fr_registerMethod(vm, "sys_BindFunc_call$7", sys_BindFunc_call__7_v); fr_registerMethod(vm, "sys_Str_intern", sys_Str_intern_v); fr_registerMethod(vm, "sys_Str_format", sys_Str_format_v); fr_registerMethod(vm, "sys_Bool_equals", sys_Bool_equals_v); fr_registerMethod(vm, "sys_Bool_not", sys_Bool_not__v); fr_registerMethod(vm, "sys_Bool_and", sys_Bool_and__v); fr_registerMethod(vm, "sys_Bool_or", sys_Bool_or__v); fr_registerMethod(vm, "sys_Bool_xor", sys_Bool_xor__v); fr_registerMethod(vm, "sys_Ptr_make", sys_Ptr_make_v); fr_registerMethod(vm, "sys_Ptr_stackAlloc", sys_Ptr_stackAlloc_v); fr_registerMethod(vm, "sys_Ptr_load", sys_Ptr_load_v); fr_registerMethod(vm, "sys_Ptr_store", sys_Ptr_store_v); fr_registerMethod(vm, "sys_Ptr_plus", sys_Ptr_plus_v); fr_registerMethod(vm, "sys_Ptr_set", sys_Ptr_set_v); fr_registerMethod(vm, "sys_Ptr_get", sys_Ptr_get_v); fr_registerMethod(vm, "sys_Array_make", sys_Array_make_v); fr_registerMethod(vm, "sys_Array_size", sys_Array_size_v); fr_registerMethod(vm, "sys_Array_get", sys_Array_get_v); fr_registerMethod(vm, "sys_Array_set", sys_Array_set_v); fr_registerMethod(vm, "sys_Array_realloc", sys_Array_realloc_v); fr_registerMethod(vm, "sys_Array_arraycopy", sys_Array_arraycopy_v); fr_registerMethod(vm, "sys_Array_finalize", sys_Array_finalize_v); fr_registerMethod(vm, "sys_NativeC_toId", sys_NativeC_toId_v); fr_registerMethod(vm, "sys_NativeC_typeName", sys_NativeC_typeName_v); fr_registerMethod(vm, "sys_NativeC_print", sys_NativeC_print_v); fr_registerMethod(vm, "sys_NativeC_printErr", sys_NativeC_printErr_v); fr_registerMethod(vm, "sys_NativeC_stackTrace", sys_NativeC_stackTrace_v); fr_registerMethod(vm, "sys_Float_makeBits", sys_Float_makeBits_v); fr_registerMethod(vm, "sys_Float_makeBits32", sys_Float_makeBits32_v); fr_registerMethod(vm, "sys_Float_fromStr", sys_Float_fromStr_v); fr_registerMethod(vm, "sys_Float_random", sys_Float_random_v); fr_registerMethod(vm, "sys_Float_equals", sys_Float_equals_v); fr_registerMethod(vm, "sys_Float_isNaN", sys_Float_isNaN_v); fr_registerMethod(vm, "sys_Float_negate", sys_Float_negate_v); fr_registerMethod(vm, "sys_Float_mult", sys_Float_mult_v); fr_registerMethod(vm, "sys_Float_multInt", sys_Float_multInt_v); fr_registerMethod(vm, "sys_Float_div", sys_Float_div_v); fr_registerMethod(vm, "sys_Float_divInt", sys_Float_divInt_v); fr_registerMethod(vm, "sys_Float_mod", sys_Float_mod_v); fr_registerMethod(vm, "sys_Float_modInt", sys_Float_modInt_v); fr_registerMethod(vm, "sys_Float_plus", sys_Float_plus_v); fr_registerMethod(vm, "sys_Float_plusInt", sys_Float_plusInt_v); fr_registerMethod(vm, "sys_Float_minus", sys_Float_minus_v); fr_registerMethod(vm, "sys_Float_minusInt", sys_Float_minusInt_v); fr_registerMethod(vm, "sys_Float_bits", sys_Float_bits_v); fr_registerMethod(vm, "sys_Float_bits32", sys_Float_bits32_v); fr_registerMethod(vm, "sys_Float_toStr", sys_Float_toStr_v); fr_registerMethod(vm, "sys_Float_toInt", sys_Float_toInt_v); fr_registerMethod(vm, "sys_Float_toLocale", sys_Float_toLocale_v); fr_registerMethod(vm, "sys_Enum_doFromStr", sys_Enum_doFromStr_v); } #endif //FR_VM
the_stack_data/34511430.c
/* --------------------------------------------------------------------- EXERCISE 3.3 ------------------------------------------------------------------------ Test the random-number generator on your system by generating N random numbers of type double between 0 and 1, transforming them to integers between 0 and r - 1 by multiplying by r and truncating the result, and computing the average and standard deviation for r = 10, 100, and 1000 and N = 10^3, 10^4, 10^5, and 10^6. --------------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <math.h> /* There is no double random number generator in the standard library. I got the following one from https://stackoverflow.com/a/33059025. It relies on rand(), so it's very low quality. */ double randfrom(double min, double max) { double range = (max - min); double div = RAND_MAX / range; return min + (rand() / div); } int main(void) { for (int r = 10; r <= 1000; r *= 10) { printf("r = %d:\n", r); for (int N = 1000; N <= 1000000; N *= 10) { float m1 = 0, m2 = 0; printf("\tN = %d:\n", N); for (int i = 0; i < N; i++) { double d = randfrom(0, 1); int x = (int)(d*r); m1 += ((float)x)/N; m2 += ((float)x*x)/N; } printf("\t\t Avg.: %f\n", m1); printf("\t\tStd. dev.: %f\n", sqrt(m2 - m1*m1)); } } } /* --------------------------------------------------------------------- OUTPUT ------------------------------------------------------------------------ r = 10: N = 1000: Avg.: 4.501000 Std. dev.: 2.870175 N = 10000: Avg.: 4.543756 Std. dev.: 2.869494 N = 100000: Avg.: 4.510306 Std. dev.: 2.868591 N = 1000000: Avg.: 4.498960 Std. dev.: 2.875373 r = 100: N = 1000: Avg.: 51.259007 Std. dev.: 28.724513 N = 10000: Avg.: 49.101334 Std. dev.: 28.924382 N = 100000: Avg.: 49.517731 Std. dev.: 28.881882 N = 1000000: Avg.: 49.555664 Std. dev.: 28.820045 r = 1000: N = 1000: Avg.: 489.583862 Std. dev.: 286.982551 N = 10000: Avg.: 501.992798 Std. dev.: 289.517298 N = 100000: Avg.: 498.855316 Std. dev.: 288.977724 N = 1000000: Avg.: 499.639801 Std. dev.: 288.386189 --------------------------------------------------------------------- */
the_stack_data/1886.c
#include <pthread.h> #include <signal.h> #include <stdlib.h> #include <fcntl.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/time.h> #include <sys/wait.h> #include <setjmp.h> #include <time.h> #include <semaphore.h> #define SEM_VALUE_MAX 65536 #define MAX_SEMAPHORE 128 #define MAX_THREADS 128 #define MAX_QUEUE 129 #define INTERVAL 50 #define ESRCH 3 enum STATE { ACTIVE, BLOCKED, EXITED, REAPED }; struct ThreadControlBlock { pthread_t ThreadID; unsigned long *ESP; enum STATE Status; void *(*start_routine)(void *); void *arg; jmp_buf Registers; int CallingThreadTCBIndex; int JustCreated; void *ReturnValue; }; struct TCBPool { /* Maximum 129 concurrent running threads including main thread whose TCB Index is 0 */ struct ThreadControlBlock TCB[MAX_THREADS + 1]; }; struct Semaphore { unsigned int ID; unsigned int Value; int semaphore_max; int Initialized; }; struct SemaphorePool { struct Semaphore semaphore[MAX_SEMAPHORE]; }; struct queue { int front; /* Init 0 */ int rear; /* Init -1 */ int itemCount; /* Init 0 */ int IndexQueue[MAX_QUEUE]; }; int peekfront(struct queue *Queue); int size(struct queue *Queue); void pushback(struct queue *Queue, int Index); void pushsecond(struct queue *Queue, int Index); int popfront(struct queue *Queue); void Scheduler(); void WrapperFunction(); void lock(); void unlock(); static long int i64_ptr_mangle(long int p); struct queue SchedulerThreadPoolIndexQueue = {0, -1, 0}; struct queue Queue[MAX_SEMAPHORE]; struct TCBPool ThreadPool; struct SemaphorePool SemPool; static int Initialized = 0; static int NextCreateTCBIndex = 1; static unsigned long ThreadID = 1; static int SemaphoreID = 0; static int SemaphoreCount = 0; static struct sigaction sigact; static struct itimerval Timer; static struct itimerval Zero_Timer = {0}; static sigset_t mask; void WrapperFunction() { int TCBIndex = peekfront(&SchedulerThreadPoolIndexQueue); void *ReturnValue = ThreadPool.TCB[TCBIndex].start_routine(ThreadPool.TCB[TCBIndex].arg); pthread_exit(ReturnValue); } void main_thread_init() { int i; for (i = 1; i < MAX_THREADS + 1; i++) { ThreadPool.TCB[i].Status = REAPED; } Initialized = 1; /* Main thread TCB Index is 0 and Main thread ID is 99999 */ ThreadPool.TCB[0].ThreadID = 99999; ThreadPool.TCB[0].Status = ACTIVE; ThreadPool.TCB[0].ESP = NULL; ThreadPool.TCB[0].start_routine = NULL; ThreadPool.TCB[0].arg = NULL; ThreadPool.TCB[0].CallingThreadTCBIndex = -1; ThreadPool.TCB[0].JustCreated = 1; ThreadPool.TCB[0].ReturnValue = NULL; pushback(&SchedulerThreadPoolIndexQueue, 0); sigact.sa_handler = Scheduler; sigemptyset(&sigact.sa_mask); sigact.sa_flags = SA_NODEFER; if (sigaction(SIGALRM, &sigact, NULL) == -1) { perror("Unable to catch SIGALRM!"); exit(1); } Timer.it_value.tv_sec = INTERVAL / 1000; Timer.it_value.tv_usec = (INTERVAL * 1000) % 1000000; Timer.it_interval = Timer.it_value; if (setitimer(ITIMER_REAL, &Timer, NULL) == -1) { perror("Error calling setitimer()"); exit(1); } setjmp(ThreadPool.TCB[0].Registers); } int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg) { /* If not initialized, initialize thread pool */ if (!Initialized) { /* Initialize the main thread pool */ main_thread_init(); } if (size(&SchedulerThreadPoolIndexQueue) < MAX_QUEUE) { /* Pause Timer */ setitimer(ITIMER_REAL, &Zero_Timer, &Timer); /* Find the next available Thread Pool slot */ int i; for (i = 1; i < MAX_QUEUE; i++) { if (ThreadPool.TCB[i].Status == REAPED) { NextCreateTCBIndex = i; break; } } /* Initialize for the chosen slot */ ThreadPool.TCB[NextCreateTCBIndex].ThreadID = ThreadID++; ThreadPool.TCB[NextCreateTCBIndex].ESP = (unsigned long *)malloc(32767); ThreadPool.TCB[NextCreateTCBIndex].Status = ACTIVE; ThreadPool.TCB[NextCreateTCBIndex].start_routine = start_routine; ThreadPool.TCB[NextCreateTCBIndex].arg = arg; ThreadPool.TCB[NextCreateTCBIndex].CallingThreadTCBIndex = -1; ThreadPool.TCB[NextCreateTCBIndex].JustCreated = 1; ThreadPool.TCB[NextCreateTCBIndex].ReturnValue = NULL; *thread = ThreadPool.TCB[NextCreateTCBIndex].ThreadID; /* Setjmp */ setjmp(ThreadPool.TCB[NextCreateTCBIndex].Registers); /* Save the address of Wrapper Function to a pointer */ void (*WrapperFunctionPointer)() = &WrapperFunction; /* Change External Stack Pointer in the jmp_buf */ ThreadPool.TCB[NextCreateTCBIndex].Registers[0].__jmpbuf[6] = i64_ptr_mangle((unsigned long)(ThreadPool.TCB[NextCreateTCBIndex].ESP + 32759 / 8 - 2)); /* Change External Instruction Pointer to Wrapper Function in the jmp_buf */ ThreadPool.TCB[NextCreateTCBIndex].Registers[0].__jmpbuf[7] = i64_ptr_mangle((unsigned long)WrapperFunctionPointer); /* Add the New Thread Thread Pool Index to the second place in the Queue in case of segfault when freeing esp of last thread with high index*/ pushback(&SchedulerThreadPoolIndexQueue, NextCreateTCBIndex); /* Resume Timer */ setitimer(ITIMER_REAL, &Timer, NULL); return 0; } /* Reach the Max number of concurrent threads and return -1 as error */ else { return -1; } } pthread_t pthread_self(void) { return (pthread_t)ThreadPool.TCB[peekfront(&SchedulerThreadPoolIndexQueue)].ThreadID; } void pthread_exit(void *value_ptr) { /* If no pthread_create call, only main */ if (Initialized == 0) { exit(0); } lock(); int Index = popfront(&SchedulerThreadPoolIndexQueue); /* If exit last thread, first free, and then exit */ if (size(&SchedulerThreadPoolIndexQueue) == 0) { if (Index != 0) { free((unsigned long *)ThreadPool.TCB[Index].ESP); } unlock(); exit(0); } /* Clean Up */ if (Index != 0) { free((unsigned long *)ThreadPool.TCB[Index].ESP); } ThreadPool.TCB[Index].ESP = NULL; ThreadPool.TCB[Index].start_routine = NULL; ThreadPool.TCB[Index].arg = NULL; ThreadPool.TCB[Index].Status = EXITED; ThreadPool.TCB[Index].ReturnValue = value_ptr; if (ThreadPool.TCB[Index].CallingThreadTCBIndex != -1) { ThreadPool.TCB[ThreadPool.TCB[Index].CallingThreadTCBIndex].Status = ACTIVE; } pushback(&SchedulerThreadPoolIndexQueue, Index); /* Longjmp to the front(next) thread registers */ Index = peekfront(&SchedulerThreadPoolIndexQueue); while (ThreadPool.TCB[Index].Status == BLOCKED || ThreadPool.TCB[Index].Status == EXITED || ThreadPool.TCB[Index].Status == REAPED) { /* If the thread is not reaped, then pushback the front Thread Pool Index of the saved thread to the end of queue */ if (ThreadPool.TCB[Index].Status != REAPED) { pushback(&SchedulerThreadPoolIndexQueue, Index); } popfront(&SchedulerThreadPoolIndexQueue); Index = peekfront(&SchedulerThreadPoolIndexQueue); } unlock(); longjmp(ThreadPool.TCB[Index].Registers, 1); } int pthread_join(pthread_t thread, void **value_ptr) { lock(); int i = 0; int found = 0; int Index = 0; int TargetThreadTCBIndex = 0; int CallingThreadTCBIndex = peekfront(&SchedulerThreadPoolIndexQueue); while (i < SchedulerThreadPoolIndexQueue.itemCount) { Index = popfront(&SchedulerThreadPoolIndexQueue); /* Find the target thread in queue */ if (ThreadPool.TCB[Index].ThreadID == thread) { found = 1; TargetThreadTCBIndex = i; /* If the thread has already been reaped, then return ESRCH */ if (ThreadPool.TCB[i].Status == REAPED) { return ESRCH; } } pushback(&SchedulerThreadPoolIndexQueue, Index); i++; } /* If not found, then return the errorno */ if (!found) { return ESRCH; } /* If the thread has already exited, then just reap it */ if (ThreadPool.TCB[TargetThreadTCBIndex].Status == EXITED) { ThreadPool.TCB[TargetThreadTCBIndex].ThreadID = 0; ThreadPool.TCB[TargetThreadTCBIndex].Status = REAPED; ThreadPool.TCB[TargetThreadTCBIndex].CallingThreadTCBIndex = -1; if (value_ptr != NULL) { *value_ptr = ThreadPool.TCB[TargetThreadTCBIndex].ReturnValue; } ThreadPool.TCB[TargetThreadTCBIndex].ReturnValue = NULL; return 0; } /* Block and store the TCB Index of calling thread */ ThreadPool.TCB[TargetThreadTCBIndex].CallingThreadTCBIndex = CallingThreadTCBIndex; ThreadPool.TCB[CallingThreadTCBIndex].Status = BLOCKED; unlock(); Scheduler(); lock(); if (value_ptr != NULL) { *value_ptr = ThreadPool.TCB[TargetThreadTCBIndex].ReturnValue; } /* Reap the Target Thread */ ThreadPool.TCB[TargetThreadTCBIndex].ThreadID = 0; ThreadPool.TCB[TargetThreadTCBIndex].Status = REAPED; ThreadPool.TCB[TargetThreadTCBIndex].CallingThreadTCBIndex = -1; ThreadPool.TCB[TargetThreadTCBIndex].ReturnValue = NULL; unlock(); /* Join succeeds */ return 0; } void Scheduler() { lock(); /* If only one main thread, just return */ if (size(&SchedulerThreadPoolIndexQueue) <= 1) { unlock(); return; } int Index = peekfront(&SchedulerThreadPoolIndexQueue); if (setjmp(ThreadPool.TCB[Index].Registers) == 0) { /* Pushback the poped front Thread Pool Index of the saved thread to the end of queue */ pushback(&SchedulerThreadPoolIndexQueue, Index); popfront(&SchedulerThreadPoolIndexQueue); Index = peekfront(&SchedulerThreadPoolIndexQueue); /* Loop through the queue if the front thread is blocked or exited */ while (ThreadPool.TCB[Index].Status == BLOCKED || ThreadPool.TCB[Index].Status == EXITED || ThreadPool.TCB[Index].Status == REAPED) { /* If the thread is not reaped, then pushback the front Thread Pool Index of the saved thread to the end of queue */ if (ThreadPool.TCB[Index].Status != REAPED) { pushback(&SchedulerThreadPoolIndexQueue, Index); } popfront(&SchedulerThreadPoolIndexQueue); Index = peekfront(&SchedulerThreadPoolIndexQueue); } if (ThreadPool.TCB[Index].JustCreated) { unlock(); ThreadPool.TCB[Index].JustCreated = 0; } /* Longjmp to the front(next) thread registers */ longjmp(ThreadPool.TCB[Index].Registers, 1); } else { unlock(); return; } } void lock() { sigemptyset(&mask); sigaddset(&mask, SIGALRM); if (sigprocmask(SIG_BLOCK, &mask, NULL) < 0) { perror("Error:"); exit(1); } } void unlock() { if (sigprocmask(SIG_UNBLOCK, &mask, NULL) < 0) { perror("Error:"); exit(1); } } int sem_init(sem_t *sem, int pshared, unsigned int value) { if (sem == NULL) { return -1; } if (pshared != 0) { return -1; } if (value > SEM_VALUE_MAX) { return -1; } int i; for (i = 0; i < MAX_SEMAPHORE; i++) { if (!SemPool.semaphore[i].Initialized) { SemaphoreID = i; break; } } lock(); SemPool.semaphore[SemaphoreID].ID = SemaphoreID; SemPool.semaphore[SemaphoreID].Value = value; SemPool.semaphore[SemaphoreID].Initialized = 1; Queue[SemaphoreID].front = 0; Queue[SemaphoreID].rear = -1; Queue[SemaphoreID].itemCount = 0; sem->__align = SemPool.semaphore[SemaphoreID].ID; SemaphoreCount++; unlock(); return 0; } int sem_destroy(sem_t *sem) { if (sem == NULL) { return -1; } lock(); int ID = sem->__align; if (!SemPool.semaphore[ID].Initialized) { return -1; } if (Queue[ID].itemCount > 0) { return -1; } SemPool.semaphore[ID].ID = 0; SemPool.semaphore[ID].Value = 0; SemPool.semaphore[ID].Initialized = 0; Queue[SemaphoreID].front = 0; Queue[SemaphoreID].rear = -1; Queue[SemaphoreID].itemCount = 0; SemaphoreCount--; unlock(); return 0; } int sem_wait(sem_t *sem) { if (sem == NULL) { return -1; } lock(); int ID = sem->__align; if (!SemPool.semaphore[ID].Initialized) { return -1; } if (SemPool.semaphore[ID].Value > 0) { SemPool.semaphore[ID].Value -= 1; unlock(); } else { int Index = peekfront(&SchedulerThreadPoolIndexQueue); ThreadPool.TCB[Index].Status = BLOCKED; pushback(&Queue[ID], Index); unlock(); Scheduler(); } } int sem_post(sem_t *sem) { if (sem == NULL) { return -1; } lock(); int ID = sem->__align; if (!SemPool.semaphore[ID].Initialized) { return -1; } if (SemPool.semaphore[ID].Value > 0) { SemPool.semaphore[ID].Value += 1; unlock(); } else { int Index = popfront(&Queue[ID]); ThreadPool.TCB[Index].Status = ACTIVE; unlock(); Scheduler(); } } int peekfront(struct queue *Queue) { return Queue->IndexQueue[Queue->front]; } int size(struct queue *Queue) { return Queue->itemCount; } void pushback(struct queue *Queue, int Index) { if (Queue->rear == MAX_QUEUE - 1) { Queue->rear = -1; } Queue->rear += 1; Queue->IndexQueue[Queue->rear] = Index; Queue->itemCount += 1; } void pushsecond(struct queue *Queue, int Index) { if (Queue->rear == MAX_QUEUE - 1) { Queue->rear = -1; } Queue->rear += 1; int i; for (i = Queue->rear; i > Queue->front + 1; i--) { Queue->IndexQueue[i] = Queue->IndexQueue[i - 1]; } Queue->IndexQueue[Queue->front + 1] = Index; Queue->itemCount += 1; } int popfront(struct queue *Queue) { int Index = Queue->IndexQueue[Queue->front]; Queue->front += 1; if (Queue->front == MAX_QUEUE) { Queue->front = 0; } Queue->itemCount -= 1; return Index; } static long int i64_ptr_mangle(long int p) { long int ret; asm(" mov %1, %%rax;\n" " xor %%fs:0x30, %%rax;" " rol $0x11, %%rax;" " mov %%rax, %0;" : "=r"(ret) : "r"(p) : "%rax"); return ret; }
the_stack_data/59981.c
/* * * * * * * * * * * * ArrayList in C * * * * * * * * * * * * * ** *By: Rafael Araújo * * * *->Info: * * * *The goal here is to practice some concepts learned in Data * *Structure class, in this case, simulate the properties and * * functionalities of an ArrayList. in this program, I'll be * *adding some extra functions to allow the user to interact with * *the list, the user be able to: * * * *1. Initialize the structure. * *2. Make the basic CRUD Operations * *3. See all the elements in the structure. * *4. See how many elements are in the structure. * *5. And more. * * * *->Copyright Notice: * * * *Copyright 2019 Rafael Araújo * * * *Permission is hereby granted, free of charge, to any person * *obtaining a copy of this software and associated documentation * *files (the "Software"), to deal in the Software without * *restriction, including without limitation the rights to use, * *copy, modify, merge, publish, distribute, sublicense, and/or * *sell copies of the Software, and to permit persons to whom the * *Software is furnished to do so, subject to the following * *conditions: * * * *THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * *EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * *OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * *NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * *HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * *WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * *FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * *OTHER DEALINGS IN THE SOFTWARE. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * **/ //Header files #include<stdio.h> #include<stdlib.h> //- - - - - - - - - - - - - - - - - - - - - - //Constants #define MAX_LENGTH 10 //- - - - - - - - - - - - - - - - - - - - - - //Global Variables typedef int ELEMENT; typedef struct{ ELEMENT value; ELEMENT* current; ELEMENT* nextElement; }NODE; typedef struct{ NODE elements[MAX_LENGTH]; ELEMENT length; }ARRAYLIST; ARRAYLIST* list; char command; NODE input; int search; ELEMENT update; int functionCall = -1; //If the list is not initialized, this will be used to alert the user to initialize it. //- - - - - - - - - - - - - - - - - - - - - - //Function signatures void setLinkedList(ARRAYLIST* list); int getLength(ARRAYLIST* list); void listCommands(); void setValue(ARRAYLIST* list, NODE value); void menu(); void getList(ARRAYLIST* list); void getOrderedList(ARRAYLIST* list); int findValue(ARRAYLIST* list, int value); int findValueByIndex(ARRAYLIST* list, int index); void updateValueByIndex(ARRAYLIST* list, int index, ELEMENT newValue); void removeFromList(ARRAYLIST* list, int index); void orderLookup(ARRAYLIST* list); //- - - - - - - - - - - - - - - - - - - - - - //Main int main(void){ list = (ARRAYLIST*)malloc(sizeof(ARRAYLIST)); printf(" ---ArrayList implementation in C---\n"); printf("Tip: The '>>' appears when you can type a command.\n"); printf("Tip: The '>' appears when you need to type inputs to the functions.\n\n"); printf("Press 'h' for help.\n"); menu(); } //-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- void menu(){ printf(">>"); scanf("%s", &command); switch(command){ case 'h': listCommands(); menu(); case 's': setLinkedList(list); menu(); case 'n': if(getLength(list)==-1){ printf("Error: list needs to be initialized.\n"); }else{ printf("Number of elements in the list: %d\n>", getLength(list)); } menu(); case 'a': system("CLS"); printf("Please, enter a value to be added: \n>"); scanf("%d", &input); setValue(list, input); menu(); case 'p': getList(list); menu(); case 'o': getOrderedList(list); menu(); case 'f': system("CLS"); if(functionCall==-1){ printf("Error: list empty or uninitialized.\n"); menu(); }else{ printf("Please, enter a number: \n>"); scanf("%d", &search); int auxSearch = findValue(list, search); if(auxSearch!=-1){ printf("Value found, list index: %d\n", auxSearch); }else{ printf("Error, value not found.\n"); } } menu(); case 'i': system("CLS"); if(functionCall!=-1){ printf("Please, enter a number: \n>"); scanf("%d", &search); if(findValueByIndex(list, search)==-1){ printf("Error: value not found or index invalid.\n"); }else{ printf("list[%d]: %d\n", search, findValueByIndex(list, search)); } }else{ printf("Error: list needs to be initialized.\n"); } menu(); case 'u': system("CLS"); if(functionCall!=-1){ printf("Please, select the position of list to be updated: "); printf("(From %d to %d):\n>", 0, list->length-1); scanf("%d", &search); printf("Please, enter the new value for this position: \n>"); scanf("%d", &update); updateValueByIndex(list, search, update); menu(); }else{ printf("Error: list empty or uninitialized.\n"); menu(); } case 'd': system("CLS"); if(functionCall==-1){ printf("Error: list empty or unitialized.\n"); menu(); }else{ printf("Please, enter the index of list to be removed: (from %d to %d)\n>", 0, list->length-1); scanf("%d", &search); removeFromList(list, search); menu(); } case 'l': system("CLS"); if(functionCall==-1){ printf("Error: list empty or uninitialized.\n"); menu(); }else{ orderLookup(list); } case 'x': printf("\nProgram Closed"); exit(0); default: system("CLS"); printf("Invalid command, press 'h' for help.\n"); menu(); } } //-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- void listCommands(){ system("CLS"); printf("List of valid commands: \n\n"); printf("'h' -> Help.\n"); printf("'s' -> Initializes the list.\n"); printf("'n' -> Get the number of elements in the list.\n"); printf("'a' -> Add a value to the end of the list. \n"); printf("'p' -> Prints the list on the screen.\n"); printf("'o' -> Shows the order of elements.\n"); printf("'f' -> Checks if a value is in the list and returns it's index.\n"); printf("'i' -> Locates a value from the list by a given index.\n"); printf("'u' -> Update a value of the list.\n"); printf("'d' -> Removes a value from the list.\n"); printf("'l' -> Shows the previous and next elements of a element in the list.\n"); printf("\n"); printf("'x' -> Close the program.\n"); } //-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- void setArrayList(ARRAYLIST* list){ system("CLS"); list->length=0; printf("Array List initialized.\n"); } //-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- int getLength(ARRAYLIST* list){ system("CLS"); if(functionCall!=-1){ return list->length; }else{ return -1; } } //-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- void setValue(ARRAYLIST* list, NODE value){ functionCall = 1; system("CLS"); if(list->length==0){ list->elements[list->length] = value; list->elements[list->length].current = (ELEMENT)list->elements[list->length].value; list->length++; printf("Element added.\n"); }else if(list->length>0 && list->length<MAX_LENGTH){ list->elements[list->length] = value; list->elements[list->length].current = (ELEMENT)list->elements[list->length].value; list->elements[list->length-1].nextElement = list->elements[list->length].current; list->length++; printf("Element added.\n"); }else if(!(list->length<0 && list->length==0 && list->length>0)){ printf("Error: list empty or uninitialized.\n"); functionCall = -1; }else{ printf("List full.\n"); } } //-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- void getList(ARRAYLIST* list){ int i; system("CLS"); printf("Linked List: \n\n"); if(functionCall==-1){ printf("Error: list empty or uninitialized.\n"); }else{ for(i=0;i<list->length;i++){ printf("%d", list->elements[i].current); if(i!=list->length-1){ printf("->"); }else{ printf("->X"); } } } printf("\n"); } //-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- void getOrderedList(ARRAYLIST* list){ int i; system("CLS"); printf("Order of elements:\n\n"); if(functionCall==-1){ printf("Error: list empty or uninitialized.\n"); }else{ printf("Current -> Next\n"); for(i=0;i<list->length;i++){ if(i!=list->length-1){ printf("%d -> %d\n", list->elements[i].current, list->elements[i].nextElement); }else{ printf("%d -> X\n", list->elements[i].current); } } } printf("\n"); } //-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- int findValue(ARRAYLIST* list, int value){ int i, index; int found = 0; system("CLS"); printf("Searching...\n"); if(functionCall!=-1){ for(i=0;i<list->length;i++){ if(list->elements[i].current==value){ found = 1; index = i; break; }else{ found = -1; } } }else{ found = -1; } if(found==1){ return index; }else{ return found; } } //-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- int findValueByIndex(ARRAYLIST* list, int index){ int i; system("CLS"); printf("Searching...\n"); if(index<=list->length && index>=0){ return list->elements[index].current; }else{ return -1; } } //-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- void updateValueByIndex(ARRAYLIST* list, int index, ELEMENT newValue){ system("CLS"); char confirmation; if(index<=list->length && index>=0){ printf("Confirm changes?(y/n): %d->%d\n", list->elements[index].current, newValue); printf(">"); scanf("%s", &confirmation); switch(confirmation){ case 'y': list->elements[index].value = newValue; list->elements[index].current = (ELEMENT)list->elements[index].value; list->elements[index-1].nextElement = list->elements[index].current; printf("Changes saved.\n"); menu(); case 'n': printf("Changes not saved.\n"); menu(); default: printf("invalid command. Press 'y' or 'n' to continue.\n>"); scanf("%s", &confirmation); } }else{ printf("Error: list index invalid.\n"); } } //-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- void removeFromList(ARRAYLIST* list, int index){ int i; char confirmation; NODE aux; if(functionCall==-1){ printf("Error: list empty or uninitialized.\n"); menu(); }else{ if(index<0 || index>list->length-1){ printf("Error: list index invalid. Try again.\n"); menu(); }else{ printf("Do you want to remove item %d?(y/n)\n>", list->elements[index].current); scanf("%s", &confirmation); switch(confirmation){ case 'y': for(i = index;i<list->length-1;i++){ list->elements[i] = list->elements[i+1]; } list->length--; list->elements[index-1].nextElement = list->elements[index].current; printf("Item removed.\n"); menu(); case 'n': printf("Item not removed.\n"); menu(); default: printf("Error: invalid command. Press 'y' or 'n' to continue.\n>"); scanf("%s", &confirmation); } } } } //-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- void orderLookup(ARRAYLIST* list){ system("CLS"); printf("Please, enter a list index (from %d to %d): \n>", 0, list->length-1); scanf("%d", &search); if(search>=0 && search<list->length){ if(search==0){ printf("\nOrder of elements:\n\n"); printf("Previous|Actual|Next\n"); printf("X |%d |%d\n", list->elements[search].current, list->elements[search].nextElement); menu(); }else if(search == list->length-1){ printf("\nOrder of elements:\n\n"); printf("Previous|Actual|Next\n"); printf("%d |%d |X\n", list->elements[search-1].current, list->elements[search].current); menu(); }else{ printf("\nOrder of elements:\n\n"); printf("Previous|Actual|Next\n"); printf("%d |%d |%d\n", list->elements[search-1].current, list->elements[search].current, list->elements[search].nextElement); menu(); } }else{ printf("Error: Index invalid.\n"); menu(); } }
the_stack_data/32951009.c
#include <stdlib.h> #include <stdio.h> #include <math.h> int main(){ int size; scanf("%d",&size); double x[size], y [size], menorx, menory, maiorx, maiory, maiordist, menordist1, menordist2, menordist3, menordist0; for ( int i=0; i<size; i++){ scanf("%lf",&x[i]); } for ( int i=0; i<size; i++){ scanf("%lf",&y[i]); } if (x[0]< x[1] && x[2]){ menorx = x[0]; } if(x[1]< x[0] && x[2]){ menorx = x[1]; } if(x[2]< x[0] && x[1]){ menorx= x[2]; } if (y[0]< y[1] && y[2]){ menory = y[0] ; } if (y[1]< y[0] && y[2]){ menory = y[1] ; } if (y[2]< y[0] && y[1]){ menory = y[2]; } if (x[0]> x[1] && x[2]){ maiorx = x[0]; }; if (x[1] > x[0] && x[2]){ maiorx = x[1]; }; if (x[2]> x[0]&& x[2]){ maiorx = x[2]; }; if (y[0] > y[1] && y[2]){ maiory = y[0]; } if (y[1] > y[0] && y[2]){ maiory = y[1]; } if (y[2] > y[1] && y[0]){ maiory = y[2]; } if ( maiory > maiorx ){ maiordist = maiory - menorx; } else{ maiordist = maiorx + fabs(menory); } if (fabs(y[0]-x[0]) < fabs(y[0]-x[1])&& fabs(y[0]-x[2])){ menordist1 = fabs(y[0]-x[0]); } if (fabs(y[0]-x[1]) < fabs(y[0]-x[0]) && fabs(y[0] - x[2])){ menordist1 = fabs(y[0] - x[1]); } if (fabs(y[0]-x[2]) < fabs(y[0]-x[0]) && fabs(y[0] - x[1])){ menordist1 = fabs(y[0]-x[2]); } if (fabs(y[1]-x[0]) < fabs(y[1]-x[1])&& fabs(y[1]-x[2])){ menordist2 = fabs(y[1]-x[0]); } if (fabs(y[1]-x[1]) < fabs(y[1]-x[0]) && fabs(y[1] - x[2])){ menordist2 = fabs(y[1] - x[1]); } if (fabs(y[1]-x[2]) < fabs(y[1]-x[0]) && fabs(y[1] -x[1])){ menordist2 = fabs(y[1]-x[2]); } if (fabs(y[2]-x[0]) < fabs(y[2]-x[1])&& fabs(y[2]-x[2])){ menordist3 = fabs(y[2]-x[0]); } if (fabs(y[2]-x[1]) < fabs(y[2]-x[0]) && fabs(y[2] - x[2])){ menordist3 = fabs(y[1] - x[1]); } if (fabs(y[2]-x[2]) < fabs(y[2]-x[0]) && fabs(y[2] - x[1])){ menordist3 = fabs(y[2]-x[2]); } if (menordist1 < menordist2 && menordist3){ menordist0 = menordist1; } if(menordist2< menordist1 && menordist3){ menordist0 = menordist2; } if(menordist3< menordist1 && menordist2){ menordist0 = menordist3; } printf("Menor Distancia: %.2lf\n",menordist0); printf("Maior Distancia: %.2lf",maiordist); }
the_stack_data/559790.c
#include<stdio.h> int main() { int i = 0, j = 1, k = 2, m; m = i++ || j++ || k++; printf("%d %d %d %d\n", m ,i ,j ,k); return 0; }
the_stack_data/636179.c
#include <dlfcn.h> #include <stdio.h> #include <stdlib.h> int main (void) { void *handle; int (*test) (int); int res; handle = dlopen ("modstatic.so", RTLD_LAZY); if (handle == NULL) { printf ("%s\n", dlerror ()); exit(1); } test = dlsym (handle, "test"); if (test == NULL) { printf ("%s\n", dlerror ()); exit(1); } res = test (2); if (res != 4) { printf ("Got %i, expected 4\n", res); exit (1); } dlclose (handle); return 0; }
the_stack_data/139672.c
/** * 字符数组转换为数值型 */ #include <stdio.h> int atoi(char s[]); int main() { char string[] = "1212121"; printf("%d\n", atoi(string)); } /* 字符数组转换为数值型 */ int atoi(char s[]) { int i, n; n = 0; for (i = 0; s[i] >= '0' && s[i] <= '9'; i++) { n = 10 * n + (s[i] - '0'); } return n; }
the_stack_data/125141859.c
/* PR target/40838 */ /* { dg-do compile { target { { ! *-*-darwin* } && ia32 } } } */ /* { dg-options "-w -mstackrealign -O3 -msse2 -mno-avx -mpreferred-stack-boundary=4" } */ float foo (float f) { float array[128]; float x = 0.; int i; for (i = 0; i < sizeof(array) / sizeof(*array); i++) array[i] = f; for (i = 0; i < sizeof(array) / sizeof(*array); i++) x += array[i]; return x; } /* { dg-final { scan-assembler "andl\[\\t \]*\\$-16,\[\\t \]*%esp" } } */
the_stack_data/16485.c
// DONE BY VERA #include <stdio.h> // Librerías // Función para detectar si el string como parámetro contiene minúsculas o no int ft_str_is_lowercase(char *str) { int i; int x; i = 0; x = 1; while (str[i] != '\0') { if (str[i] >= 'a' && str[i] <= 'z') { x = x * 1; } else { x = 0; } i++; } return (x); } // Función main int main(void) { char *str = "buenas"; char *str2 = "BUENAS"; char *str3 = "bue8nas"; int a = ft_str_is_lowercase(str); int b = ft_str_is_lowercase(str2); int c = ft_str_is_lowercase(str3); printf("1- %i\n", a); printf("2- %i\n", b); printf("3- %i\n", c); }
the_stack_data/32950381.c
#include<arpa/inet.h> #include<netinet/in.h> #include<signal.h> #include<stdbool.h> #include<stdio.h> #include<stdlib.h> #include<string.h> #include<sys/socket.h> #include<unistd.h> #include<time.h> #define WIDTH (1<<10) #define HEIGHT (1<<9) #define MAXPLAYERS (1<<5) /// RESPONSES char errResp[] = "HTTP/1.1 404 Not Found\r\n" "Content-Type: text/html; charset=UTF-8\r\n" "Connection: close\r\nCache-Control: no-cache\r\n" "Content-Length: 94\r\n" "\r\n" "404 Not Found (or something else for which I can't be bothered to make a proper error message)"; char errFullResp[] = "HTTP/1.1 503 Server Full\r\n" "Content-Type: text/html; charset=UTF-8\r\n" "Connection: close\r\nCache-Control: no-cache\r\n" "Content-Length: 35\r\n" "\r\n" "Sorry, The server is full right now"; char chunkedHeaders[] = "HTTP/1.1 200 OK\r\n" "Content-Type: text/html; charset=UTF-8\r\n" "Connection: close\r\n" "X-Content-Type-Options: nosniff\r\n" "Cache-Control: no-cache\r\n" "Transfer-Encoding: Chunked\r\n\r\n"; char startResp[] = "HTTP/1.1 200 OK\r\n" "Content-Type: text/html; charset=UTF-8\r\n" "Connection: close\r\n" "Content-Length: 161\r\n" "\r\n" "<html><body><script>" "form=document.createElement('form');" "form.method='POST';" "form.action='/';" "document.body.appendChild(form);" "form.submit()" "</script></body></html>"; char okResp[] = "HTTP/1.1 204 No Content\r\n" "Connection: close\r\n" //"Cache-Control: no-cache\r\n" "Content-Length: 0\r\n\r\n"; char initChunk[10009]; // WIDTH=1024, 4*(1026/3)= 1368 #define DATASIZE (2*HEIGHT) char dataChunk[4*((DATASIZE+2)/3)+31] = "56C\r\n" "\n<script>" "d(\"X"; char* dataStart; char startChunk[] = "__\r\n" "<script>" "tok=\"TTTTTTTTTTTT\";" "plnum=NNNNNN;" "start(XXXX ,YYYY ,WWWW ,HHHH );" "</script>" "\r\n"; char* starttok; char* startplnum; char* startp[2]; char* startsz[2]; char newplayerChunk[] = "XX\r\n" "<script>" "np(NNNNN ,XXXX ,YYYY )" "</script>\n" "\r\n"; char* npdata; FILE * randFile; ///UTILS int snd(int sock, char* msg){ printf("\nsending message to socket %d\n",sock); int l = strlen(msg); if (l<100) puts(msg); while (l>0){ int c = send(sock,msg,l,0); printf("sent: %d\n",c); if(c<0){perror("send failed"); close(sock); return -1;} msg+=c; l-=c; } return 0; } char tohexdig(int n){ if(n<10) return 0x30+n; else return 0x61-10+n; } unsigned int readnat(char** s){ unsigned int n=0; while(**s>='0' && **s<='9'){ n = n*10 + **s - '0'; (*s)++; } return n; } int getrandom(char* x, int l, int no_idea){ return fread(x,1,l,randFile); } char b64[64] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; unsigned char b64inv[256]; char* b64e(unsigned char* in, unsigned char* out, int len){ int c=0; int tmp=0; while(len--){ tmp |= *(in++); if((++c)%3==0){ for(int i=0;i<4;i++){ *(out++)=b64[(tmp>>18)&0x3F]; tmp<<=6; } tmp=0; } else tmp<<=8; } int k = c%3; if(k){ tmp<<=(2-k)*8; for(int i=0;i<4;i++){ *(out++) = i>k?'=':b64[(tmp>>18)&0x3F]; tmp<<=6; } } return out; } unsigned char* b64d(unsigned char* in, unsigned char* out, int len){ int lenin = (len/3)*4 + ((len%3)*3+1)/2; int tmp=0; int c=0; while(b64inv[*in]!=0xFF && c<lenin){ tmp |= b64inv[*(in++)]; if(++c%4==0){ for(int i=0;i<3;i++){ *(out++)=(tmp>>16)&0xFF; tmp<<=8; } tmp=0; } else tmp<<=6; } int k = c%4; if(k){ tmp<<=(3-k)*6; for(int i=0;i<k-1;i++){ *(out++)=(tmp>>16)&0xFF; tmp<<=8; } } return in; } void b64setup(){ for(int i=0;i<256;i++) b64inv[i]=0xFF; for(char i=0;i<64;i++) b64inv[b64[i]]=i; /*TESTING char s[100] = "XXXXXXXXXX"; int x = b64d("UVdFUlQ=",s,5); // s[x]='\0'; printf("%d %s\n",x, s); exit(0);*/ } ///STRUCTS typedef unsigned short cell; // 0 means off, 1 means on but unowned cell base[WIDTH][HEIGHT]; cell backup[WIDTH][HEIGHT]; cell (*grid)[HEIGHT] = base; struct player{ int conn; unsigned long token; short move[2]; int ref; }; typedef struct player player; player players[1<<16]; int ixs[MAXPLAYERS]; int plays[MAXPLAYERS]; int numplays; int playing; int width; //for dynamic resizing int height; cell (*next)[HEIGHT] = backup; //GoL cell get(int x, int y){ return grid[(width+x%width)%width][(height+y%height)%height]; } void step(){ for(int x=0;x<width;x++) for(int y=0;y<height;y++){ cell v=grid[x][y]; if(v){ int numset=0; for(int i=-1;i<2;i++) for(int j=-1;j<2;j++) if(i||j) {if(get(x+i,y+j)) numset+=1;} next[x][y]=((numset==2 || numset==3)* v); }else{ cell fst = 0; cell snd = 0; cell res = 0; for(int i=-1;i<2;i++) for(int j=-1;j<2;j++) if(i||j){ cell k=get(x+i,y+j); if(k){ if(snd && !fst) res=0; else if (snd){ if(fst==snd || fst==k) res=fst; else if (snd==k) res=snd; else res=1; fst=0; } else { snd=fst; fst=k; } } } next[x][y]=res; /* for(int i=-1;i<2;i++) for(int j=-1;j<2;j++) if (i||j){ cell k = get(x+i,y+j); }*/ } } void* tmp=grid; grid=next; next=tmp; } /// PLAYER HANDLING int remove_player(int idx){ printf("removing player %d\n",idx); if(!players[idx].conn) return 1; //close socket? - No becuase snd already does that players[idx].conn=0; int r = players[idx].ref; ixs[r] = ixs[--playing]; players[ixs[r]].ref=r; return 0; // Consider decolouring cells belonging to the player // Performance considerations apply if many disconnect simultaneously } /// SENDING DATA int sendDataChunk(int sock, char* dat,int len){ char* nxt = b64e(dat, dataStart, len); strcpy(nxt, "\")</script>\r\n"); int x = strlen(dataChunk)-7; dataChunk[0]=tohexdig(x>>8); dataChunk[1]=tohexdig((x>>4)&0xF); dataChunk[2]=tohexdig(x&0xF); return snd(sock, dataChunk); } int sendData(int sock){ int i=0; while(i<width){ if(sendDataChunk(sock, ((char*)grid[i]), height*2)) return -1; i++; } //return sendDataChunk(sock, ((char*)grid)+i*DATASIZE, 2*width*height - i*); return 0; } int sendStart(int idx, short* startpos ){ sprintf(startp[0],"%4d ,%4d ,%4d ,%4d", startpos[0],startpos[1],width,height); startsz[1][4]=' '; sprintf(startplnum,"%6d",idx); startplnum[6]=';'; b64e((char*) &players[idx].token, starttok, sizeof(long)); return snd(players[idx].conn,startChunk); } void send_all(char* msg){ printf("sending to all: "); puts(msg); int l=strlen(msg); while(l>0){ int i=0; int sz=l<1024?l:1024; while(i<playing){ int idx=ixs[i]; if (players[idx].ref!=i) printf("prob: %d,%d,%d\n",i,idx,players[idx].ref); int k=sz; char* t=msg; int c; int sock = players[idx].conn; if(sock==0){ printf("problem: %d\n",idx); i+=1;continue; } while(k>0){ c = send(sock,t,k,0); if(c<0)break; k-=c; t+=c; } if(c<0){ close(sock); remove_player(idx); } else i++; } l-=sz; msg+=sz; } } char stepChunk[10*MAXPLAYERS+33]="XXXX\r\n" "<script>tick("; char* moveData; void startScript(){ moveData=stepChunk+19; } void addMove(unsigned short* x){ moveData+=sprintf(moveData,"%d,%d,",x[0],x[1]); } void endScript(){ moveData=strcpy(moveData,");</script>\n\r\n"); sprintf(stepChunk,"%04x",moveData-stepChunk+14-8); stepChunk[4]='\r'; } void sendNewPlayer(int idx, short* xy){ sprintf(npdata, "%5d ,%4d ,%4d", idx, xy[0], xy[1]); npdata[5+2+4+2+4]=' '; send_all(newplayerChunk); } /// REQUEST HANDLERS void tick(){ step(); int i=0; startScript(); while(i<numplays){ unsigned short* x = players[plays[i]].move; if(x[0]<width && x[1]<height && grid[x[0]][x[1]]==0){ //Add move to script addMove(x); grid[x[0]][x[1]]=1; } players[plays[i]].move[0]=-1; i++; } numplays=0; // Consider changing width/height //Send script to everyone endScript(); send_all(stepChunk); } int new_player(int sock){ if(playing>=MAXPLAYERS){ if(!snd(sock,errFullResp)) close(sock); return -1; } // Setup players and ixs cell idx; getrandom((char*)&idx,sizeof(idx),0); idx = (idx&0x7FFF)|0x8000; while(players[idx].conn)idx=((idx+1)&0x7FFF)|0x8000; getrandom((char*)&players[idx].token,sizeof(long) ,0); players[idx].conn=sock; players[idx].move[0]=-1; players[idx].ref=playing; // Setup start location short startpos[2]; getrandom((char*)startpos, 2* sizeof(short) ,0); startpos[0]=(width+startpos[0]%width)%width; startpos[1]=(height+startpos[1]%height)%height; for(int i=width-2;i<width+4;i++) for(int j=height-2;j<height+4;j++){ grid[(i+startpos[0])%width][(j+startpos[1])%height]=((i&2)||(j&2))?0:idx; printf("%d,%d:%d\n", (i+startpos[0])%width, (j+startpos[1])%height,grid[(i+startpos[0])%width][(j+startpos[1])%height]); } sendNewPlayer(idx,startpos); ixs[playing ++]=idx; if(snd(sock,chunkedHeaders) || snd(sock,initChunk) || sendStart(idx,startpos) || sendData(sock) ){ remove_player(idx); } return 0; } int play_move(char* request){ unsigned int idx = readnat(&request); if(*(request++)!='/') return -1; if(idx>(1<<16) || players[idx].conn==0) return -1; long t; // printf("%d, %d\n",idx,players[idx].move[0]); request=b64d(request,(unsigned char*) &t, sizeof(long)); if(t!=players[idx].token)return -1; while(*request=='=')request++; if(*(request++)!='/') return -1; unsigned int x=readnat(&request); if(x>=width || *(request++)!='/') return -1; unsigned int y=readnat(&request); if(y>=height) return -1; if (players[idx].move[0]==-1)plays[numplays++]=idx; players[idx].move[0]=x; players[idx].move[1]=y; return 0; } #define CHECK(cond)\ if(!(cond)){\ snd(sock,errResp);\ close(sock);\ return;\ } void handle(int sock, char* request){ if(memcmp(request,"GET ",4)==0){ request+=4; if (memcmp(request,"/ ",2)==0) snd(sock,startResp); /* else if(memcmp(request,"/hammer.min.js ",15)==0) snd(sock,hammerResp);*/ else { snd(sock,errResp); /*CHECK(*(request++) =='/') unsigned int x=readnat(&request); CHECK(*(request++) =='/') unsigned int y=readnat(&request); printf("%d\n",grid[x][y]); snd(sock,okResp); */ } } else if(memcmp(request,"POST ",5)==0){ request+=5; CHECK(*(request++) =='/') if (*request==' '){ new_player(sock); return;// don't close socket } // Playing a move if (play_move(request)) snd(sock,errResp); else snd(sock, okResp); } else CHECK(false) close(sock); } /// Initialization int mkChunk(char* str){ int l = strlen(str) - 6; // xx/r/nbody/r/n if (l>=256 || l<0){ return -1; } str[0] = tohexdig(l/16); str[1] = tohexdig(l%16); puts(str); return 0; } int setup(){ b64setup(); if (mkChunk(startChunk)) return -1; if (mkChunk(newplayerChunk)) return -1; starttok = strchr(startChunk,'T'); startplnum = strchr(startChunk,'N'); startp[0] = strchr(startChunk,'X'); startp[1] = strchr(startChunk,'Y'); startsz[0] = strchr(startChunk,'W'); startsz[1] = strchr(startChunk,'H'); dataStart = strchr(dataChunk,'X'); npdata = strchr(newplayerChunk,'N'); randFile = fopen("/dev/urandom","r"); if (randFile==0){return -6;} FILE * file = fopen("init.html","r"); if (file==0){return -2;} int k = fread(initChunk+6,1,10000,file); if(ferror(file)) return -3; if(!feof(file)) return -4; sprintf(initChunk,"%04x\r",k); initChunk[5]='\n'; sprintf(initChunk+k+6,"\r\n"); fclose(file); /* file = fopen("hammer.min.js","r"); if (file==0){return -2;} int l = strlen(hammerResp); k = fread(hammerResp+l+9,1,22000,file); if(ferror(file)) return -3; if(!feof(file)) return -4; int eight=sprintf(hammerResp+l,"%5d\r\n\r",k); if(eight!=8) return -5; hammerResp[l+eight]='\n'; sprintf(hammerResp+l+eight+k,"\r\n");*/ width=64; height=64; return 0; } time_t prev; // TODO: 'safe' should probably be atomic or something bool safe; void alrm(int x){ if(safe){ time_t new = time(0); if(new!=prev){ tick(); prev=new; } } alarm(1); } int main(){ puts("let's begin"); int c=setup(); if (c){ printf("setup failed %d\n",c); return 1; } int sock_listen; sock_listen = socket(AF_INET, SOCK_STREAM, 0); if (sock_listen <0){ puts("Could not create socket"); return 1; } signal(SIGPIPE, SIG_IGN); signal(SIGALRM, alrm); alarm(1); //Really helps debugging int enable = 1; setsockopt(sock_listen, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)); /*struct timeval timeout; timeout.tv_sec=0; timeout.tv_usec=100000; if(setsockopt(sock_listen, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout))<0){ puts("setting timeout failed"); return 1; }*/ struct sockaddr_in server, client; server.sin_addr.s_addr = INADDR_ANY; server.sin_family = AF_INET; server.sin_port = htons(8080); if ( bind(sock_listen, (struct sockaddr *) &server, sizeof(server)) <0){ perror("bind failed"); return 1; } listen(sock_listen, 10); puts("Listening"); while(true){ int k; safe=true; int new_socket = accept(sock_listen, (struct sockaddr*) &client, (socklen_t*) &k); safe=false; if(new_socket>0){ char request[101]; int c = recv(new_socket, request,100, 0); if(c>0){ request[c]=0; printf("count: %d\n",c); puts(request); handle(new_socket,request); } else{ perror("recv failed"); close(new_socket); } } time_t new = time(0); if(new!=prev){ tick(); prev=new; } } return 0; }
the_stack_data/29824080.c
/******************************************************************************* * * Copyright (C) 2014-2018 Wave Computing, Inc. * * 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. * ******************************************************************************/ #include <wchar.h> wchar_t * wmemset (wchar_t *s, wchar_t c, size_t n) { wchar_t *p = (wchar_t *) s; while (n) { *p++ = c; --n; } return s; }
the_stack_data/1002609.c
#include <stdio.h> int main(){ int n, m; scanf("%d %d", &n, &m); int arr[n][m]; int i, j; for(i = 0; i < n; i ++){ for(j = 0; j < m; j ++){ scanf("%d", &arr[i][j]); } } for(i = 0; i < n; i ++){ for(j = 0; j < m; j ++){ printf("%d ", arr[i][j]); } printf("\n"); } return 0; }
the_stack_data/880037.c
#include <errno.h> #include <sys/types.h> #include <sys/stat.h> void _exit(void) { while (1) __asm__("hlt"); } caddr_t program_break, program_break_end; caddr_t sbrk(int incr) { if (program_break == 0 || program_break + incr >= program_break_end) { errno = ENOMEM; return (caddr_t)-1; } caddr_t prev_break = program_break; program_break += incr; return prev_break; } int getpid(void) { return 1; } int kill(int pid, int sig) { errno = EINVAL; return -1; } int close(int fd) { errno = EBADF; return -1; } off_t lseek(int fd, off_t offset, int whence) { errno = EBADF; return -1; } int open(const char* path, int flags) { errno = ENOENT; return -1; } ssize_t read(int fd, void* buf, size_t count) { errno = EBADF; return -1; } ssize_t write(int fd, const void* buf, size_t count) { errno = EBADF; return -1; } int fstat(int fd, struct stat* buf) { errno = EBADF; return -1; } int isatty(int fd) { errno = EBADF; return -1; }
the_stack_data/54825202.c
#include<stdio.h> #include<stdlib.h> #include<string.h> typedef struct Person { int id; char name[20]; int age; struct Person *next; }Person; struct Person *list, *firstPointer, *auxiliar; int idGen = 0; int queueSize = 0; int validAnswer(){ char answer; do{ printf("\n\n Would you like to continue [Y/N]: "); fflush(stdin); scanf("%c", &answer); answer = toupper(answer); }while(answer != 'Y' && answer != 'N'); if(answer == 'Y'){ system("cls"); return 0; }else{ return 1; } } void enterData(){ printf("\n Enter user data:\n"); idGen++; auxiliar = (Person*) malloc(sizeof(Person)); auxiliar->id = idGen; printf("\n Inform user name: "); scanf("%s", &auxiliar->name); printf(" Inform user age: "); scanf("%d", &auxiliar->age); } void enqueue(){ queueSize++; enterData(); if(firstPointer == NULL){ auxiliar->next = NULL; list = auxiliar; firstPointer = auxiliar; }else { auxiliar->next = NULL; list->next = auxiliar; list = auxiliar; } } void findAll(){ auxiliar = firstPointer; if(auxiliar == NULL){ printf("\n There is no user registered."); }else { printf("\n Users Registered:"); while(auxiliar != NULL){ printf("\n ID = %d Name = %s Age = %d", auxiliar->id, auxiliar->name, auxiliar->age); auxiliar=auxiliar->next; } } } void sequeue(int id){ auxiliar = firstPointer; int notFound = 0; if(auxiliar == NULL){ printf("\n There is no user registered."); notFound = 1; }else { int position = 0; while(auxiliar != NULL){ position++; if(auxiliar->id == id){ printf("\n User searched at position %d", position); notFound = 1; break; } auxiliar = auxiliar->next; } } if(notFound == 0){ printf("\n ID: %d not found.", id); } } void dequeue(){ auxiliar = firstPointer; if(auxiliar == NULL){ printf("\n There is no user registered."); }else { firstPointer = auxiliar->next; free(auxiliar); queueSize--; } } int main(){ list = NULL; firstPointer = NULL; auxiliar = NULL; int id; do{ int option; system("cls"); printf("\n Queue"); printf("\n----------------------------\n"); printf("\n Choose option:"); printf("\n 1: Insert new user"); printf("\n 2: Show users"); printf("\n 3: Remove user"); printf("\n 4: Search user queue position"); printf("\n"); scanf("%d", &option); switch(option){ case 1: system("cls"); if (queueSize == 4){ printf("\n Stackoverflow"); return; } enqueue(); break; case 2: system("cls"); findAll(); break; case 3: system("cls"); dequeue(); break; case 4: system("cls"); int pos; printf("\n Inform user ID: "); scanf("%d", &pos); sequeue(pos); break; default: printf("\n Invalid option"); } }while(validAnswer() == 0 && queueSize < 5); // Simulate memory size with a int number }
the_stack_data/193892156.c
/* Carlos Eduardo Cirilo Kelly Kaoru Tanikawa Renato Mitsuo Umino */ #include <stdio.h> typedef char string[100]; int leitura(string *s) { if (gets(*s) != NULL) return 1; else return 0; } void decodifica(string *s) { int i = 0; while ((*s)[i] != '\0') { if ((*s)[i] != ' ') { switch((*s)[i]) { case '1': (*s)[i] = '`'; break; case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': (*s)[i]--; break; case '0': (*s)[i] = '9'; break; case '-': (*s)[i] = '0'; break; case '=': (*s)[i] = '-'; break; case 'W': (*s)[i] = 'Q'; break; case 'E': (*s)[i] = 'W'; break; case 'R': (*s)[i] = 'E'; break; case 'T': (*s)[i] = 'R'; break; case 'Y': (*s)[i] = 'T'; break; case 'U': (*s)[i] = 'Y'; break; case 'I': (*s)[i] = 'U'; break; case 'O': (*s)[i] = 'I'; break; case 'P': (*s)[i] = 'O'; break; case '[': (*s)[i] = 'P'; break; case ']': (*s)[i] = '['; break; case '\\': (*s)[i] = ']'; break; case 'S': (*s)[i] = 'A'; break; case 'D': (*s)[i] = 'S'; break; case 'F': (*s)[i] = 'D'; break; case 'G': (*s)[i] = 'F'; break; case 'H': (*s)[i] = 'G'; break; case 'J': (*s)[i] = 'H'; break; case 'K': (*s)[i] = 'J'; break; case 'L': (*s)[i] = 'K'; break; case ';': (*s)[i] = 'L'; break; case '\'': (*s)[i] = ';'; break; case 'X': (*s)[i] = 'Z'; break; case 'C': (*s)[i] = 'X'; break; case 'V': (*s)[i] = 'C'; break; case 'B': (*s)[i] = 'V'; break; case 'N': (*s)[i] = 'B'; break; case 'M': (*s)[i] = 'N'; break; case ',': (*s)[i] = 'M'; break; case '.': (*s)[i] = ','; break; case '/': (*s)[i] = '.'; break; } } ++i; } return; } int main() { string s; while (leitura(&s)) { decodifica(&s); printf("%s\n",s); } return 0; }