file
stringlengths
18
26
data
stringlengths
3
1.04M
the_stack_data/93886967.c
// Copyright 2019 The gRPC Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // When building for Unity Android with il2cpp backend, Unity tries to link // the __Internal PInvoke definitions (which are required by iOS) even though // the .so/.dll will be actually used. This file provides dummy stubs to // make il2cpp happy. // See https://github.com/grpc/grpc/issues/16012 #include <stdio.h> #include <stdlib.h> void grpcsharp_init() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_shutdown() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_version_string() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_batch_context_create() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_batch_context_recv_initial_metadata() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_batch_context_recv_message_length() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_batch_context_recv_message_next_slice_peek() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_batch_context_recv_status_on_client_status() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_batch_context_recv_status_on_client_details() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_batch_context_recv_status_on_client_trailing_metadata() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_batch_context_recv_close_on_server_cancelled() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_batch_context_reset() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_batch_context_destroy() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_request_call_context_create() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_request_call_context_call() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_request_call_context_method() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_request_call_context_host() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_request_call_context_deadline() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_request_call_context_request_metadata() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_request_call_context_reset() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_request_call_context_destroy() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_composite_call_credentials_create() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_credentials_release() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_cancel() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_cancel_with_status() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_start_unary() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_start_client_streaming() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_start_server_streaming() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_start_duplex_streaming() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_send_message() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_send_close_from_client() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_send_status_from_server() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_recv_message() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_recv_initial_metadata() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_start_serverside() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_send_initial_metadata() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_set_credentials() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_get_peer() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_destroy() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_channel_args_create() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_channel_args_set_string() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_channel_args_set_integer() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_channel_args_destroy() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_override_default_ssl_roots() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_ssl_credentials_create() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_composite_channel_credentials_create() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_channel_credentials_release() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_insecure_channel_create() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_secure_channel_create() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_channel_create_call() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_channel_check_connectivity_state() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_channel_watch_connectivity_state() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_channel_get_target() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_channel_destroy() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_sizeof_grpc_event() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_completion_queue_create_async() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_completion_queue_create_sync() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_completion_queue_shutdown() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_completion_queue_next() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_completion_queue_pluck() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_completion_queue_destroy() { fprintf(stderr, "Should never reach here"); abort(); } void gprsharp_free() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_metadata_array_create() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_metadata_array_add() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_metadata_array_count() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_metadata_array_get_key() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_metadata_array_get_value() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_metadata_array_destroy_full() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_redirect_log() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_native_callback_dispatcher_init() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_metadata_credentials_create_from_plugin() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_metadata_credentials_notify_from_plugin() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_ssl_server_credentials_create() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_server_credentials_release() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_server_create() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_server_register_completion_queue() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_server_add_insecure_http2_port() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_server_add_secure_http2_port() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_server_start() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_server_request_call() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_server_cancel_all_calls() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_server_shutdown_and_notify_callback() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_server_destroy() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_call_auth_context() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_auth_context_peer_identity_property_name() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_auth_context_property_iterator() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_auth_property_iterator_next() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_auth_context_release() { fprintf(stderr, "Should never reach here"); abort(); } void gprsharp_now() { fprintf(stderr, "Should never reach here"); abort(); } void gprsharp_inf_future() { fprintf(stderr, "Should never reach here"); abort(); } void gprsharp_inf_past() { fprintf(stderr, "Should never reach here"); abort(); } void gprsharp_convert_clock_type() { fprintf(stderr, "Should never reach here"); abort(); } void gprsharp_sizeof_timespec() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_test_callback() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_test_nop() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_test_override_method() { fprintf(stderr, "Should never reach here"); abort(); } void grpcsharp_test_call_start_unary_echo() { fprintf(stderr, "Should never reach here"); abort(); }
the_stack_data/234517185.c
/* * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #include <stdio.h> #ifdef _WIN32 #include <winsock2.h> #include <ws2tcpip.h> #else #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> #endif /** * Generates sun.nio.ch.SocketOptionRegistry, a class that maps Java-level * socket options to the platform specific level and option. */ static void out(char* s) { printf("%s\n", s); } static void emit(const char *name, char * family, int level, int optname) { printf(" map.put(new RegistryKey(%s, %s),", name, family); printf(" new OptionKey(%d, %d));\n", level, optname); } static void emit_unspec(const char *name, int level, int optname) { emit(name, "Net.UNSPEC", level, optname); } static void emit_inet(const char *name, int level, int optname) { emit(name, "StandardProtocolFamily.INET", level, optname); } static void emit_inet6(const char *name, int level, int optname) { emit(name, "StandardProtocolFamily.INET6", level, optname); } int main(int argc, const char* argv[]) { out("// AUTOMATICALLY GENERATED FILE - DO NOT EDIT "); out("package sun.nio.ch; "); out("import java.net.SocketOption; "); out("import java.net.StandardSocketOptions; "); out("import java.net.ProtocolFamily; "); out("import java.net.StandardProtocolFamily; "); out("import java.util.Map; "); out("import java.util.HashMap; "); out("class SocketOptionRegistry { "); out(" private SocketOptionRegistry() { } "); out(" private static class RegistryKey { "); out(" private final SocketOption<?> name; "); out(" private final ProtocolFamily family; "); out(" RegistryKey(SocketOption<?> name, ProtocolFamily family) { "); out(" this.name = name; "); out(" this.family = family; "); out(" } "); out(" public int hashCode() { "); out(" return name.hashCode() + family.hashCode(); "); out(" } "); out(" public boolean equals(Object ob) { "); out(" if (ob == null) return false; "); out(" if (!(ob instanceof RegistryKey)) return false; "); out(" RegistryKey other = (RegistryKey)ob; "); out(" if (this.name != other.name) return false; "); out(" if (this.family != other.family) return false; "); out(" return true; "); out(" } "); out(" } "); out(" private static class LazyInitialization { "); out(" static final Map<RegistryKey,OptionKey> options = options(); "); out(" private static Map<RegistryKey,OptionKey> options() { "); out(" Map<RegistryKey,OptionKey> map = "); out(" new HashMap<RegistryKey,OptionKey>(); "); emit_unspec("StandardSocketOptions.SO_BROADCAST", SOL_SOCKET, SO_BROADCAST); emit_unspec("StandardSocketOptions.SO_KEEPALIVE", SOL_SOCKET, SO_KEEPALIVE); emit_unspec("StandardSocketOptions.SO_LINGER", SOL_SOCKET, SO_LINGER); emit_unspec("StandardSocketOptions.SO_SNDBUF", SOL_SOCKET, SO_SNDBUF); emit_unspec("StandardSocketOptions.SO_RCVBUF", SOL_SOCKET, SO_RCVBUF); emit_unspec("StandardSocketOptions.SO_REUSEADDR", SOL_SOCKET, SO_REUSEADDR); emit_unspec("StandardSocketOptions.TCP_NODELAY", IPPROTO_TCP, TCP_NODELAY); emit_inet("StandardSocketOptions.IP_TOS", IPPROTO_IP, IP_TOS); emit_inet("StandardSocketOptions.IP_MULTICAST_IF", IPPROTO_IP, IP_MULTICAST_IF); emit_inet("StandardSocketOptions.IP_MULTICAST_TTL", IPPROTO_IP, IP_MULTICAST_TTL); emit_inet("StandardSocketOptions.IP_MULTICAST_LOOP", IPPROTO_IP, IP_MULTICAST_LOOP); #ifdef AF_INET6 emit_inet6("StandardSocketOptions.IP_MULTICAST_IF", IPPROTO_IPV6, IPV6_MULTICAST_IF); emit_inet6("StandardSocketOptions.IP_MULTICAST_TTL", IPPROTO_IPV6, IPV6_MULTICAST_HOPS); emit_inet6("StandardSocketOptions.IP_MULTICAST_LOOP", IPPROTO_IPV6, IPV6_MULTICAST_LOOP); #endif emit_unspec("ExtendedSocketOption.SO_OOBINLINE", SOL_SOCKET, SO_OOBINLINE); out(" return map; "); out(" } "); out(" } "); out(" public static OptionKey findOption(SocketOption<?> name, ProtocolFamily family) { "); out(" RegistryKey key = new RegistryKey(name, family); "); out(" return LazyInitialization.options.get(key); "); out(" } "); out("} "); return 0; }
the_stack_data/73576372.c
// KASAN: slab-out-of-bounds Write in crypto_dh_encode_key // https://syzkaller.appspot.com/bug?id=a84d6ad70b281bfc5632f272f745104fb43d219d // status:fixed // autogenerated by syzkaller (http://github.com/google/syzkaller) #define _GNU_SOURCE #include <endian.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <sys/syscall.h> #include <unistd.h> uint64_t r[6] = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0}; void loop() { long res = 0; memcpy((void*)0x20000340, "keyring", 8); *(uint8_t*)0x20000380 = 0x73; *(uint8_t*)0x20000381 = 0x79; *(uint8_t*)0x20000382 = 0x7a; *(uint8_t*)0x20000383 = 0; *(uint8_t*)0x20000384 = 0; res = syscall(__NR_add_key, 0x20000340, 0x20000380, 0, 0, 0xfffffffe); if (res != -1) r[0] = res; memcpy((void*)0x20000400, "keyring", 8); *(uint8_t*)0x200003c0 = 0x73; *(uint8_t*)0x200003c1 = 0x79; *(uint8_t*)0x200003c2 = 0x7a; *(uint8_t*)0x200003c3 = 0; *(uint8_t*)0x200003c4 = 0; res = syscall(__NR_add_key, 0x20000400, 0x200003c0, 0, 0, r[0]); if (res != -1) r[1] = res; memcpy((void*)0x20000040, "user", 5); *(uint8_t*)0x20000080 = 0x73; *(uint8_t*)0x20000081 = 0x79; *(uint8_t*)0x20000082 = 0x7a; *(uint8_t*)0x20000083 = 0; *(uint8_t*)0x20000084 = 0; memcpy((void*)0x200001c0, "\xda", 1); res = syscall(__NR_add_key, 0x20000040, 0x20000080, 0x200001c0, 1, r[1]); if (res != -1) r[2] = res; memcpy((void*)0x200000c0, "keyring", 8); *(uint8_t*)0x20000180 = 0x73; *(uint8_t*)0x20000181 = 0x79; *(uint8_t*)0x20000182 = 0x7a; *(uint8_t*)0x20000183 = 0; *(uint8_t*)0x20000184 = 0; res = syscall(__NR_add_key, 0x200000c0, 0x20000180, 0, 0, r[1]); if (res != -1) r[3] = res; memcpy((void*)0x203bd000, "user", 5); *(uint8_t*)0x20000280 = 0x73; *(uint8_t*)0x20000281 = 0x79; *(uint8_t*)0x20000282 = 0x7a; *(uint8_t*)0x20000283 = 0; *(uint8_t*)0x20000284 = 0; memcpy((void*)0x20000440, "", 1); res = syscall(__NR_add_key, 0x203bd000, 0x20000280, 0x20000440, 1, r[3]); if (res != -1) r[4] = res; memcpy((void*)0x20fc0ffb, "user", 5); *(uint8_t*)0x20752ffb = 0x73; *(uint8_t*)0x20752ffc = 0x79; *(uint8_t*)0x20752ffd = 0x7a; *(uint8_t*)0x20752ffe = 0x23; *(uint8_t*)0x20752fff = 0; memcpy((void*)0x203eb000, "\xb3", 1); res = syscall(__NR_add_key, 0x20fc0ffb, 0x20752ffb, 0x203eb000, 1, r[3]); if (res != -1) r[5] = res; *(uint32_t*)0x200006c0 = r[4]; *(uint32_t*)0x200006c4 = r[5]; *(uint32_t*)0x200006c8 = r[2]; *(uint64_t*)0x20c61fc8 = 0x20a3dffa; memcpy((void*)0x20a3dffa, "\x73\x68\x61\x35\x31\x32\x2d\x67\x65\x6e\x65\x72\x69\x63\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", 64); *(uint64_t*)0x20c61fd0 = 0; *(uint32_t*)0x20c61fd8 = 0; *(uint32_t*)0x20c61fdc = 0; *(uint32_t*)0x20c61fe0 = 0; *(uint32_t*)0x20c61fe4 = 0; *(uint32_t*)0x20c61fe8 = 0; *(uint32_t*)0x20c61fec = 0; *(uint32_t*)0x20c61ff0 = 0; *(uint32_t*)0x20c61ff4 = 0; *(uint32_t*)0x20c61ff8 = 0; syscall(__NR_keyctl, 0x17, 0x200006c0, 0x20000540, 5, 0x20c61fc8); } int main() { syscall(__NR_mmap, 0x20000000, 0x1000000, 3, 0x32, -1, 0); loop(); return 0; }
the_stack_data/100514.c
int i; int contador;
the_stack_data/127252.c
#include <stdio.h> #undef setbuf void setbuf(FILE * restrict fp, char * restrict buf) { setvbuf(fp, buf, (buf) ? _IOFBF : _IONBF, BUFSIZ); }
the_stack_data/115766809.c
#include <stdio.h> #include <stdlib.h> typedef struct _nodo { int dato; struct _nodo* sx; struct _nodo* dx; } nodo; nodo* Inserisci(nodo* radice, int input) { if(radice==NULL) { nodo* nuovo = malloc(sizeof(nodo)); (*nuovo).dato = input; (*nuovo).sx = NULL; (*nuovo).dx = NULL; return nuovo; } else { if(input <= (*radice).dato) (*radice).sx = Inserisci((*radice).sx, input); else (*radice).dx = Inserisci((*radice).dx, input); return radice; } } void SegnaPercorso(nodo* radice, int* percorso, int cercato, int i) // -1 letto elemento NULL // -2 fine dei valori significativi { if(radice == NULL) { percorso[i] = -1; percorso[i+1] = -2; } else { percorso[i] = (*radice).dato; if(cercato == (*radice).dato) percorso[i+1] = -2; else { if(cercato < (*radice).dato) SegnaPercorso((*radice).sx, percorso, cercato, i+1); else SegnaPercorso((*radice).dx, percorso, cercato, i+1); } } } int main() { int n, k; scanf("%d %d", &n, &k); //Crea gli alberi e legge i valori dei nodi nodo* radice1 = NULL; nodo* radice2 = NULL; int i; for(i=0; i<n; i++) { int input; scanf("%d", &input); radice1 = Inserisci(radice1, input); } for(i=0; i<n; i++) { int input; scanf("%d", &input); radice2 = Inserisci(radice2, input); } //Compila gli array dei percorsi seguiti nella ricerca di k int* percorso1 = malloc(n * sizeof(int)); int* percorso2 = malloc(n * sizeof(int)); SegnaPercorso(radice1, percorso1, k, 0); SegnaPercorso(radice2, percorso2, k, 0); i=0; int uguali=1; while(uguali==1 && percorso1[i] != -2 && percorso2[i] != -2) { if(percorso1[i] != percorso2[i]) uguali=0; i++; } printf("%d\n", uguali); return 0; }
the_stack_data/92325230.c
#include <assert.h> #include <stdio.h> signed char set[400] = { 8, 2,22,97,38,15, 0,40, 0,75, 4, 5, 7,78,52,12,50,77,91, 8, 49,49,99,40,17,81,18,57,60,87,17,40,98,43,69,48, 4,56,62, 0, 81,49,31,73,55,79,14,29,93,71,40,67,53,88,30, 3,49,13,36,65, 52,70,95,23, 4,60,11,42,69,24,68,56, 1,32,56,71,37, 2,36,91, 22,31,16,71,51,67,63,89,41,92,36,54,22,40,40,28,66,33,13,80, 24,47,32,60,99, 3,45, 2,44,75,33,53,78,36,84,20,35,17,12,50, 32,98,81,28,64,23,67,10,26,38,40,67,59,54,70,66,18,38,64,70, 67,26,20,68, 2,62,12,20,95,63,94,39,63, 8,40,91,66,49,94,21, 24,55,58,05,66,73,99,26,97,17,78,78,96,83,14,88,34,89,63,72, 21,36,23, 9,75, 0,76,44,20,45,35,14, 0,61,33,97,34,31,33,95, 78,17,53,28,22,75,31,67,15,94,03,80, 4,62,16,14, 9,53,56,92, 16,39, 5,42,96,35,31,47,55,58,88,24, 0,17,54,24,36,29,85,57, 86,56, 0,48,35,71,89, 7, 5,44,44,37,44,60,21,58,51,54,17,58, 19,80,81,68, 5,94,47,69,28,73,92,13,86,52,17,77, 4,89,55,40, 4,52, 8,83,97,35,99,16, 7,97,57,32,16,26,26,79,33,27,98,66, 88,36,68,87,57,62,20,72, 3,46,33,67,46,55,12,32,63,93,53,69, 4,42,16,73,38,25,39,11,24,94,72,18, 8,46,29,32,40,62,76,36, 20,69,36,41,72,30,23,88,34,62,99,69,82,67,59,85,74, 4,36,16, 20,73,35,29,78,31,90, 1,74,31,49,71,48,86,81,16,23,57,05,54, 1,70,54,71,83,51,54,69,16,92,33,48,61,43,52, 1,89,19,67,48, }; static int fetch(int x, int y) { assert(x >= 0); assert(y >= 0); assert(x < 20); assert(y < 20); int a = x + (20 * y); assert(a >= 0); assert(a < 400); int ret = set[a]; assert(ret >= 0); assert(ret <= 99); return set[a]; } static int horizontal(void) { int max = 0; for (int y = 0; y < 20; y++) { for (int x = 0; x < (20 - 4); x++) { int tmp = fetch(x + 0, y) * fetch(x + 1, y) * fetch(x + 2, y) * fetch(x + 3, y); if (tmp > max) { max = tmp; } } } return max; } static int vertical(void) { int max = 0; for (int y = 0; y < (20 - 4); y++) { for (int x = 0; x < 20; x++) { int tmp = fetch(x, y + 0) * fetch(x, y + 1) * fetch(x, y + 2) * fetch(x, y + 3); if (tmp > max) { max = tmp; } } } return max; } static int backSlash(void) { int max = 0; for (int y = 0; y < (20 - 4); y++) { for (int x = 0; x < (20 - 4); x++) { int tmp = fetch(x + 0, y + 0) * fetch(x + 1, y + 1) * fetch(x + 2, y + 2) * fetch(x + 3, y + 3); if (tmp > max) { max = tmp; } } } return max; } static int forwardSlash(void) { int max = 0; for (int y = 0; y < (20 - 4); y++) { for (int x = 3; x < 20; x++) { int tmp = fetch(x - 0, y + 0) * fetch(x - 1, y + 1) * fetch(x - 2, y + 2) * fetch(x - 3, y + 3); if (tmp > max) { max = tmp; } } } return max; } int maxProduct(void) { int tmp = 0; int a = forwardSlash(); int b = backSlash(); int c = vertical(); int d = horizontal(); printf("a: %d\n", a); printf("b: %d\n", b); printf("c: %d\n", c); printf("d: %d\n", d); if (a > b) { tmp = a; } else { tmp = b; } if (c > tmp) { tmp = c; } if (d > tmp) { tmp = d; } return tmp; }
the_stack_data/232956634.c
/** * 影视剧测试 */ #include "stdio.h" #include "string.h" #define TSIZE 45 /* 存储片名的数组大小 */ #define FMAX 5 /*影片的最大数量*/ struct film { char title[TSIZE]; int rating; }; char * s_gets(char str[], int lim); int main(void){ struct film movies[FMAX]; int i =0 ; int j; puts("Enter first movie title: "); while (i < FMAX && s_gets(movies[i].title ,TSIZE) != NULL && movies[i].title[0] !='\0') { puts("Enter your rating <0 - 10>: "); scanf("%d", &movies[i++].rating); while (getchar() !='\n' ) continue; puts("Enter next movie title (empty line to stop): "); } if(i == 0){ printf("No data entered."); }else{ printf(" Here is the movie list: \n"); } for(j=0; j< i; j++){ printf("Moive: %s Rating: %d\n", movies[j].title,movies[j].rating); } return 0; }
the_stack_data/187642886.c
#include <stdio.h> #include <stdlib.h> #include <math.h> struct Node { int coeff; int exp; struct Node *next; }*poly=NULL; void create() { struct Node *t,*last=NULL; int num,i; printf("Enter number of terms: "); scanf("%d",&num); printf("Enter each term with coeff and exp\n"); for(i=0;i<num;i++) { t=(struct Node *)malloc(sizeof(struct Node)); scanf("%d%d",&t->coeff,&t->exp); t->next=NULL; if(poly==NULL) { poly=last=t; } else { last->next=t; last=t; } } } void Display(struct Node *p) { while(p) { printf("%dx^%d +",p->coeff,p->exp); p=p->next; } printf("\n"); } long Eval(struct Node *p, int x) { long val=0; while(p) { val+=p->coeff*pow(x,p->exp); p=p->next; } return val; } int main() { create(); Display(poly); printf("%ld\n",Eval(poly,1)); return 0; }
the_stack_data/126702944.c
/** * Double Free * https://cwe.mitre.org/data/definitions/415.html */ #include <stdbool.h> #include <stdlib.h> int main() { char * buffer = (char *) malloc(256); bool error = true; if (error) free(buffer); // [...] free(buffer); // second free }
the_stack_data/100141252.c
#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; #ifdef _MSC_VER static inline _Fcomplex Cf(complex *z) {_Fcomplex zz={z->r , z->i}; return zz;} static inline _Dcomplex Cd(doublecomplex *z) {_Dcomplex zz={z->r , z->i};return zz;} static inline _Fcomplex * _pCf(complex *z) {return (_Fcomplex*)z;} static inline _Dcomplex * _pCd(doublecomplex *z) {return (_Dcomplex*)z;} #else 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;} #endif #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)); } #ifdef _MSC_VER #define c_div(c, a, b) {Cf(c)._Val[0] = (Cf(a)._Val[0]/Cf(b)._Val[0]); Cf(c)._Val[1]=(Cf(a)._Val[1]/Cf(b)._Val[1]);} #define z_div(c, a, b) {Cd(c)._Val[0] = (Cd(a)._Val[0]/Cd(b)._Val[0]); Cd(c)._Val[1]=(Cd(a)._Val[1]/df(b)._Val[1]);} #else #define c_div(c, a, b) {pCf(c) = Cf(a)/Cf(b);} #define z_div(c, a, b) {pCd(c) = Cd(a)/Cd(b);} #endif #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) = conjf(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) (cimagf(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; } #ifdef _MSC_VER static _Fcomplex cpow_ui(complex x, integer n) { complex pow={1.0,0.0}; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x.r = 1/x.r, x.i=1/x.i; for(u = n; ; ) { if(u & 01) pow.r *= x.r, pow.i *= x.i; if(u >>= 1) x.r *= x.r, x.i *= x.i; else break; } } _Fcomplex p={pow.r, pow.i}; return p; } #else 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; } #endif #ifdef _MSC_VER static _Dcomplex zpow_ui(_Dcomplex x, integer n) { _Dcomplex pow={1.0,0.0}; unsigned long int u; if(n != 0) { if(n < 0) n = -n, x._Val[0] = 1/x._Val[0], x._Val[1] =1/x._Val[1]; for(u = n; ; ) { if(u & 01) pow._Val[0] *= x._Val[0], pow._Val[1] *= x._Val[1]; if(u >>= 1) x._Val[0] *= x._Val[0], x._Val[1] *= x._Val[1]; else break; } } _Dcomplex p = {pow._Val[0], pow._Val[1]}; return p; } #else 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; } #endif 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; #ifdef _MSC_VER _Fcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conjf(Cf(&x[i]))._Val[0] * Cf(&y[i])._Val[0]; zdotc._Val[1] += conjf(Cf(&x[i]))._Val[1] * Cf(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conjf(Cf(&x[i*incx]))._Val[0] * Cf(&y[i*incy])._Val[0]; zdotc._Val[1] += conjf(Cf(&x[i*incx]))._Val[1] * Cf(&y[i*incy])._Val[1]; } } pCf(z) = zdotc; } #else _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; } #endif static inline void zdotc_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Dcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conj(Cd(&x[i]))._Val[0] * Cd(&y[i])._Val[0]; zdotc._Val[1] += conj(Cd(&x[i]))._Val[1] * Cd(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += conj(Cd(&x[i*incx]))._Val[0] * Cd(&y[i*incy])._Val[0]; zdotc._Val[1] += conj(Cd(&x[i*incx]))._Val[1] * Cd(&y[i*incy])._Val[1]; } } pCd(z) = zdotc; } #else _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; } #endif static inline void cdotu_(complex *z, integer *n_, complex *x, integer *incx_, complex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Fcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cf(&x[i])._Val[0] * Cf(&y[i])._Val[0]; zdotc._Val[1] += Cf(&x[i])._Val[1] * Cf(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cf(&x[i*incx])._Val[0] * Cf(&y[i*incy])._Val[0]; zdotc._Val[1] += Cf(&x[i*incx])._Val[1] * Cf(&y[i*incy])._Val[1]; } } pCf(z) = zdotc; } #else _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; } #endif static inline void zdotu_(doublecomplex *z, integer *n_, doublecomplex *x, integer *incx_, doublecomplex *y, integer *incy_) { integer n = *n_, incx = *incx_, incy = *incy_, i; #ifdef _MSC_VER _Dcomplex zdotc = {0.0, 0.0}; if (incx == 1 && incy == 1) { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cd(&x[i])._Val[0] * Cd(&y[i])._Val[0]; zdotc._Val[1] += Cd(&x[i])._Val[1] * Cd(&y[i])._Val[1]; } } else { for (i=0;i<n;i++) { /* zdotc = zdotc + dconjg(x(i))* y(i) */ zdotc._Val[0] += Cd(&x[i*incx])._Val[0] * Cd(&y[i*incy])._Val[0]; zdotc._Val[1] += Cd(&x[i*incx])._Val[1] * Cd(&y[i*incy])._Val[1]; } } pCd(z) = zdotc; } #else _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 DORM2L multiplies a general matrix by the orthogonal matrix from a QL factorization determined by sgeqlf (unblocked algorithm). */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* > \htmlonly */ /* > Download DORM2L + dependencies */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/dorm2l. f"> */ /* > [TGZ]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/dorm2l. f"> */ /* > [ZIP]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/dorm2l. f"> */ /* > [TXT]</a> */ /* > \endhtmlonly */ /* Definition: */ /* =========== */ /* SUBROUTINE DORM2L( SIDE, TRANS, M, N, K, A, LDA, TAU, C, LDC, */ /* WORK, INFO ) */ /* CHARACTER SIDE, TRANS */ /* INTEGER INFO, K, LDA, LDC, M, N */ /* DOUBLE PRECISION A( LDA, * ), C( LDC, * ), TAU( * ), WORK( * ) */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > */ /* > DORM2L overwrites the general real m by n matrix C with */ /* > */ /* > Q * C if SIDE = 'L' and TRANS = 'N', or */ /* > */ /* > Q**T * C if SIDE = 'L' and TRANS = 'T', or */ /* > */ /* > C * Q if SIDE = 'R' and TRANS = 'N', or */ /* > */ /* > C * Q**T if SIDE = 'R' and TRANS = 'T', */ /* > */ /* > where Q is a real orthogonal matrix defined as the product of k */ /* > elementary reflectors */ /* > */ /* > Q = H(k) . . . H(2) H(1) */ /* > */ /* > as returned by DGEQLF. Q is of order m if SIDE = 'L' and of order n */ /* > if SIDE = 'R'. */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \param[in] SIDE */ /* > \verbatim */ /* > SIDE is CHARACTER*1 */ /* > = 'L': apply Q or Q**T from the Left */ /* > = 'R': apply Q or Q**T from the Right */ /* > \endverbatim */ /* > */ /* > \param[in] TRANS */ /* > \verbatim */ /* > TRANS is CHARACTER*1 */ /* > = 'N': apply Q (No transpose) */ /* > = 'T': apply Q**T (Transpose) */ /* > \endverbatim */ /* > */ /* > \param[in] M */ /* > \verbatim */ /* > M is INTEGER */ /* > The number of rows of the matrix C. M >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in] N */ /* > \verbatim */ /* > N is INTEGER */ /* > The number of columns of the matrix C. N >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in] K */ /* > \verbatim */ /* > K is INTEGER */ /* > The number of elementary reflectors whose product defines */ /* > the matrix Q. */ /* > If SIDE = 'L', M >= K >= 0; */ /* > if SIDE = 'R', N >= K >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in] A */ /* > \verbatim */ /* > A is DOUBLE PRECISION array, dimension (LDA,K) */ /* > The i-th column must contain the vector which defines the */ /* > elementary reflector H(i), for i = 1,2,...,k, as returned by */ /* > DGEQLF in the last k columns of its array argument A. */ /* > A is modified by the routine but restored on exit. */ /* > \endverbatim */ /* > */ /* > \param[in] LDA */ /* > \verbatim */ /* > LDA is INTEGER */ /* > The leading dimension of the array A. */ /* > If SIDE = 'L', LDA >= f2cmax(1,M); */ /* > if SIDE = 'R', LDA >= f2cmax(1,N). */ /* > \endverbatim */ /* > */ /* > \param[in] TAU */ /* > \verbatim */ /* > TAU is DOUBLE PRECISION array, dimension (K) */ /* > TAU(i) must contain the scalar factor of the elementary */ /* > reflector H(i), as returned by DGEQLF. */ /* > \endverbatim */ /* > */ /* > \param[in,out] C */ /* > \verbatim */ /* > C is DOUBLE PRECISION array, dimension (LDC,N) */ /* > On entry, the m by n matrix C. */ /* > On exit, C is overwritten by Q*C or Q**T*C or C*Q**T or C*Q. */ /* > \endverbatim */ /* > */ /* > \param[in] LDC */ /* > \verbatim */ /* > LDC is INTEGER */ /* > The leading dimension of the array C. LDC >= f2cmax(1,M). */ /* > \endverbatim */ /* > */ /* > \param[out] WORK */ /* > \verbatim */ /* > WORK is DOUBLE PRECISION array, dimension */ /* > (N) if SIDE = 'L', */ /* > (M) if SIDE = 'R' */ /* > \endverbatim */ /* > */ /* > \param[out] INFO */ /* > \verbatim */ /* > INFO is INTEGER */ /* > = 0: successful exit */ /* > < 0: if INFO = -i, the i-th argument had an illegal value */ /* > \endverbatim */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date December 2016 */ /* > \ingroup doubleOTHERcomputational */ /* ===================================================================== */ /* Subroutine */ int dorm2l_(char *side, char *trans, integer *m, integer *n, integer *k, doublereal *a, integer *lda, doublereal *tau, doublereal * c__, integer *ldc, doublereal *work, integer *info) { /* System generated locals */ integer a_dim1, a_offset, c_dim1, c_offset, i__1, i__2; /* Local variables */ logical left; integer i__; extern /* Subroutine */ int dlarf_(char *, integer *, integer *, doublereal *, integer *, doublereal *, doublereal *, integer *, doublereal *); extern logical lsame_(char *, char *); integer i1, i2, i3, mi, ni, nq; extern /* Subroutine */ int xerbla_(char *, integer *, ftnlen); logical notran; doublereal aii; /* -- LAPACK computational 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 */ /* ===================================================================== */ /* Test the input arguments */ /* Parameter adjustments */ a_dim1 = *lda; a_offset = 1 + a_dim1 * 1; a -= a_offset; --tau; c_dim1 = *ldc; c_offset = 1 + c_dim1 * 1; c__ -= c_offset; --work; /* Function Body */ *info = 0; left = lsame_(side, "L"); notran = lsame_(trans, "N"); /* NQ is the order of Q */ if (left) { nq = *m; } else { nq = *n; } if (! left && ! lsame_(side, "R")) { *info = -1; } else if (! notran && ! lsame_(trans, "T")) { *info = -2; } else if (*m < 0) { *info = -3; } else if (*n < 0) { *info = -4; } else if (*k < 0 || *k > nq) { *info = -5; } else if (*lda < f2cmax(1,nq)) { *info = -7; } else if (*ldc < f2cmax(1,*m)) { *info = -10; } if (*info != 0) { i__1 = -(*info); xerbla_("DORM2L", &i__1, (ftnlen)6); return 0; } /* Quick return if possible */ if (*m == 0 || *n == 0 || *k == 0) { return 0; } if (left && notran || ! left && ! notran) { i1 = 1; i2 = *k; i3 = 1; } else { i1 = *k; i2 = 1; i3 = -1; } if (left) { ni = *n; } else { mi = *m; } i__1 = i2; i__2 = i3; for (i__ = i1; i__2 < 0 ? i__ >= i__1 : i__ <= i__1; i__ += i__2) { if (left) { /* H(i) is applied to C(1:m-k+i,1:n) */ mi = *m - *k + i__; } else { /* H(i) is applied to C(1:m,1:n-k+i) */ ni = *n - *k + i__; } /* Apply H(i) */ aii = a[nq - *k + i__ + i__ * a_dim1]; a[nq - *k + i__ + i__ * a_dim1] = 1.; dlarf_(side, &mi, &ni, &a[i__ * a_dim1 + 1], &c__1, &tau[i__], &c__[ c_offset], ldc, &work[1]); a[nq - *k + i__ + i__ * a_dim1] = aii; /* L10: */ } return 0; /* End of DORM2L */ } /* dorm2l_ */
the_stack_data/466495.c
/** ****************************************************************************** * @file stm32f4xx_ll_crc.c * @author MCD Application Team * @version V1.7.1 * @date 14-April-2017 * @brief CRC LL module driver. ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2017 STMicroelectronics</center></h2> * * 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 STMicroelectronics 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. * ****************************************************************************** */ #if defined(USE_FULL_LL_DRIVER) /* Includes ------------------------------------------------------------------*/ #include "stm32f4xx_ll_crc.h" #include "stm32f4xx_ll_bus.h" #ifdef USE_FULL_ASSERT #include "stm32_assert.h" #else #define assert_param(expr) ((void)0U) #endif /** @addtogroup STM32F4xx_LL_Driver * @{ */ #if defined (CRC) /** @addtogroup CRC_LL * @{ */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup CRC_LL_Exported_Functions * @{ */ /** @addtogroup CRC_LL_EF_Init * @{ */ /** * @brief De-initialize CRC registers (Registers restored to their default values). * @param CRCx CRC Instance * @retval An ErrorStatus enumeration value: * - SUCCESS: CRC registers are de-initialized * - ERROR: CRC registers are not de-initialized */ ErrorStatus LL_CRC_DeInit(CRC_TypeDef *CRCx) { ErrorStatus status = SUCCESS; /* Check the parameters */ assert_param(IS_CRC_ALL_INSTANCE(CRCx)); if (CRCx == CRC) { /* Force CRC reset */ LL_AHB1_GRP1_ForceReset(LL_AHB1_GRP1_PERIPH_CRC); /* Release CRC reset */ LL_AHB1_GRP1_ReleaseReset(LL_AHB1_GRP1_PERIPH_CRC); } else { status = ERROR; } return (status); } /** * @} */ /** * @} */ /** * @} */ #endif /* defined (CRC) */ /** * @} */ #endif /* USE_FULL_LL_DRIVER */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
the_stack_data/140806.c
// RUN: %clang_cc1 -emit-llvm %s -o /dev/null /* GCC was not escaping quotes in string constants correctly, so this would * get emitted: * %.LC1 = internal global [32 x sbyte] c"*** Word "%s" on line %d is not\00" */ const char *Foo() { return "*** Word \"%s\" on line %d is not"; }
the_stack_data/7950080.c
// Developed by Dileepa Bandara #include<stdio.h> void free_data() { printf("\n ---------------- Apply For Bonus Data ---------------- \n"); int employee_no;\ printf("\n Enter your employee number: "); scanf("%d", &employee_no); int plan; printf("\n Select your current Internet Plan \n "); printf("\tPress 1 for Home Plan Rs. 120/= \n"); printf("\tPress 2 for Lite Plan Rs. 200/= \n"); printf("\tPress 3 for Pro Plan Rs. 300/= \n"); printf("\n Select: "); scanf("%d", &plan); if (plan == 1) { printf("\t Home Plan \n"); printf("\t 20 GB \n"); printf("\t Rs. 120/= \n"); printf("\n Your data has been added to your account of %d" , employee_no); } else if (plan == 2) { printf("\t Home Plan \n"); printf("\t 40 GB \n"); printf("\t Rs. 200/= \n"); printf("\n Your data has been added to your account of %d" , employee_no); } else if (plan == 3) { printf("\t Home Plan \n"); printf("\t 80 GB \n"); printf("\t Rs. 300/= \n"); printf("\n Your data has been added to your account of %d" , employee_no); } else { printf("Enter a valid answer"); printf("\n Thank You \n\n"); } //menu(); } void bonus_salary() { printf("\n ---------------- Apply For Bonus Salary ---------------- \n"); int employee_no;\ printf("\n Enter your employee number: "); scanf("%d", &employee_no); float salary; printf(" Enter your current salary: "); scanf("%f", &salary); if ( salary <= 10000 ) { float bonus = salary * 0.7; float current_salary = bonus + salary; printf("\n Your Previous Salary = %0.2f", salary); printf("\n Your Bonus = %0.2f", bonus); printf("\n Your Current Salary = %0.2f", current_salary); printf("\n Your bonus has been added to your account of %d" , employee_no); printf("\n Thank You \n\n"); } else if ( salary <= 20000 ) { float bonus = salary * 0.5; float current_salary = bonus + salary; printf("\n Your Previous Salary = %0.2f", salary); printf("\n Your Bonus = %0.2f", bonus); printf("\n Your Current Salary = %0.2f", current_salary); printf("\n Your bonus has been added to your account of %d" , employee_no); printf("\n Thank You \n\n"); } else if (salary <= 30000) { float bonus = salary * 0.3; float current_salary = bonus + salary; printf("\n Your Previous Salary = %0.2f", salary); printf("\n Your Bonus = %0.2f", bonus); printf("\n Your Current Salary = %0.2f", current_salary); printf("\n Your bonus has been added to your account of %d" , employee_no); printf("\n Thank You \n\n"); } else { printf("\n Sorry You Cannot Apply For This"); printf("\n Thank You \n\n"); } //menu(); } void menu() { int a; printf("\n ---------------------------------------------------- \n"); printf("\tPress 1 to Apply for Bonus Data \n"); printf("\tPress 2 to Apply for Bonus Salary \n"); printf("\tPress Other button exit \n"); printf("\n Press: "); scanf("%d", &a); if(a == 1) { free_data(); } else if(a == 2) { bonus_salary(); } else { printf("\n Thank You For Use Service \n\n"); } } void main () { printf("\n\t\t########## BONUS PACKAGE ########## \n\n"); printf(" Hello Employee! Due to the COVID-19 pandemic we offers you bonus packages \n"); menu(); }
the_stack_data/190767618.c
#include<stdio.h> #define PI 3.1415926 #define MAX 10 int get_year(float R) { int i=0; double area=PI*R/2; int sum; //待估计的每年丢失的面积 while((sum=i*50+1)<area) { i++; } return i; } int main() { float a,b,max; int N,i; int c[MAX]; scanf("%d",&N); for(i=0;i<N;i++) { scanf("%f%f",&a,&b); //本来用到引号中有分号,那么就读不进去第二数了。 max=a*a+b*b; c[i]=get_year(max); } for(i=0;i<N;i++) { printf("Property %d:This property will begin eroding in year %d。\n",i+1,c[i]); } printf("END OF OUTPUT。\n"); return 0; }
the_stack_data/234518193.c
/* { dg-do run } */ /* { dg-require-effective-target int128 } */ /* { dg-options "-fsanitize=signed-integer-overflow" } */ /* 2^127 - 1 */ #define INT128_MAX (__int128) (((unsigned __int128) 1 << ((__SIZEOF_INT128__ * __CHAR_BIT__) - 1)) - 1) #define INT128_MIN (-INT128_MAX - 1) int main (void) { volatile __int128 i = INT128_MAX; volatile __int128 j = 1; volatile __int128 k = i + j; k = j + i; i++; j = INT128_MAX - 100; j += (1 << 10); j = INT128_MIN; i = -1; k = i + j; k = j + i; j--; j = INT128_MIN + 100; j += -(1 << 10); i = INT128_MAX; j = 2; k = i * j; i = INT128_MIN; i = -i; return 0; } /* { dg-output "signed integer overflow: 0x7fffffffffffffffffffffffffffffff \\+ 1 cannot be represented in type '__int128'(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]*signed integer overflow: 1 \\+ 0x7fffffffffffffffffffffffffffffff cannot be represented in type '__int128'(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]*signed integer overflow: 0x7fffffffffffffffffffffffffffffff \\+ 1 cannot be represented in type '__int128'(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]*signed integer overflow: 0x7fffffffffffffffffffffffffffff9b \\+ 1024 cannot be represented in type '__int128'(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]*signed integer overflow: -1 \\+ 0x80000000000000000000000000000000 cannot be represented in type '__int128'(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]*signed integer overflow: 0x80000000000000000000000000000000 \\+ -1 cannot be represented in type '__int128'(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]*signed integer overflow: 0x80000000000000000000000000000000 - 1 cannot be represented in type '__int128'(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]*signed integer overflow: 0x80000000000000000000000000000064 \\+ -1024 cannot be represented in type '__int128'(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]*signed integer overflow: 0x7fffffffffffffffffffffffffffffff \\* 2 cannot be represented in type '__int128'(\n|\r\n|\r)" } */ /* { dg-output "\[^\n\r]*negation of 0x80000000000000000000000000000000 cannot be represented in type '__int128'; cast to an unsigned type to negate this value to itself" } */
the_stack_data/128244.c
#include<stdio.h> #include<stdlib.h> struct node{ int data; struct node *next; }; typedef struct node NODE; NODE *head1=NULL; NODE *head2=NULL; NODE *getnode(){ int e; NODE *newnode; newnode=(NODE*)malloc(sizeof(NODE)); printf("\nenter the value of the element\n"); scanf("%d",&e); newnode->data=e; newnode->next=NULL; } NODE* insert_front_end(NODE*head){ NODE *newnode; newnode=getnode(); newnode->next=head; head=newnode; display(head); return head; } NODE* insert_last_end(NODE*head){ NODE *newnode,*cur; if(head==NULL){ insert_front_end(head); return head; } newnode=getnode(); cur=head; while(cur->next!=NULL){ cur=cur->next; } cur->next=newnode; display(head); return head; } NODE* delete_front_end(NODE*head){ if(head==NULL){ printf("\ndeletion is not possible as list is already empty"); return head ; } NODE*temp; temp=head; head=temp->next; free(temp); display(head); return head; } NODE* delete_last_end(NODE*head){ NODE *pre,*cur; cur=head; if(head==NULL){ printf("\ndeletion is not possible as list is already empty"); return head ; } if(head->next==NULL){ printf("\nonly one element was in list which has deleted"); head=NULL; free(head); return head; } while(cur->next!=NULL){ pre=cur; cur=cur->next; } cur=pre->next; pre->next=NULL; free(cur); display(head); return head; } void display(NODE*head){ NODE*cur; cur=head; if(cur==NULL){ printf("\nlinked list is empty"); return ; } while(cur!=NULL){ printf("%d->",cur->data); cur=cur->next; } } NODE* insert_i_position(NODE*head){ NODE *newnode,*cur; int count,i; cur=head; count=0; if(cur==NULL){ printf("list is empty so u can insert at only front\n"); insert_front_end(head); return head; } printf("\nenter the position where you want to insert"); scanf("%d",&i); while(cur->next!=NULL){ cur=cur->next; count++; } newnode=getnode(head); if(i>count+2){ printf("\ninsertion at thius position is not posibble"); } else if(i==count+2){ cur->next=newnode; display(head); } else{ cur=head; count=1; while(count!=i-1){ count++; cur=cur->next; } newnode->next=cur->next; cur->next=newnode; display(head); return head; } } NODE* delete_i_position(NODE*head){ NODE*prev,*cur; int i,count; printf("\nenter the position number where you want to delete"); scanf("%d",&i); count=1; cur=head; if(cur==NULL){ printf("\nlist is empty"); return head; } if(cur->next==NULL){ if(i==1){ head=head->next; free(cur); printf("\nthe only element of the list has been deleted"); return head; } else{ printf("\noperation cannot be performed"); return head; } } while(cur!=NULL){ cur=cur->next; count++; } if(count<i){ printf("\ndeleteion is not possible as i postion is not exist"); return head; } else{ cur=head; count=1; while(count!=i){ count++; prev=cur; cur=cur->next; } prev->next=cur->next; free(cur); display(head); return head; } } NODE* union_list(){ NODE *cur,*prev,*head; head=NULL; cur=NULL; if(head1->data ==head2->data){ cur=head1; head=cur; head1=head1->next; prev=head; cur=cur->next; head2=head2->next; } else if(head1->data > head2->data){ cur=head2; head=cur; head2=head2->next; prev=head; cur=cur->next; } else if(head1->data < head2->data){ cur=head1; head=cur; head1=head1->next; prev=head; cur=cur->next; } while(head1!=NULL&&head2!=NULL){ if(head1->data ==head2->data){ cur=head1; prev->next=cur; head1=head1->next; prev=cur; cur=cur->next; head2=head2->next; } else if(head1->data > head2->data){ cur=head2; prev->next=head2; head2=head2->next; prev=cur; cur=cur->next; } else if(head1->data < head2->data){ cur=head1; head1=head1->next; prev->next=cur; prev=cur; cur=cur->next; } } if(head1==NULL){ cur=head2; return head; } if(head2==NULL){ cur=head1; return head; } } int main(){ int ch; NODE* head; printf("list element should be sorted "); while(1){ printf("\nyou can choose among following operation"); printf("\n1.insert at front in 1st list\n2.insert at end in 1st list\n3.delete at frontin first list\n4.deletet at end in first list\n5.insert at ith positio in first list\n6. delete at ith positionin 1st list\n"); printf("7.display 1st list"); printf("\n 8.insert at front in 2nd list \n 9.insert at end in the 2nd list\n10.delete at front in 2nd list\n11.delete at end in 2nd list\n12.insert at ith position in the 2nd list\n13. delete at ith position in the 2nd list\n14.display 2nd list\n15. union of the lists\16.exit\n"); printf("\nenter your choice\n"); scanf("%d",&ch); if(ch>=16){ return; } switch(ch){ case 1: head1=insert_front_end(head1); break; case 2 : head1=insert_last_end(head1); break; case 3 : head1=delete_front_end(head1); break; case 4 : delete_last_end(head1); break; case 5 : head1=insert_i_position(head1); break; case 6 : head1=delete_i_position(head1); break; case 7 : display(head1); break; case 8: head2=insert_front_end(head2); break; case 9 : head2=insert_last_end(head2); break; case 10: head2=delete_front_end(head2); break; case 11: delete_last_end(head2); break; case 12: head2=insert_i_position(head2); break; case 13: head2=delete_i_position(head2); break; case 14 : display(head2); break; case 15 : head=union_list(); display(head); } } }
the_stack_data/148576693.c
#include <stdio.h> #include <string.h> int main (void) { char correct_pass[] = "test"; char typed_pass[10]; do { printf ("\nTo unlock your last tip, enter the correct password: "); scanf ("%s", typed_pass); } while (strcmp(typed_pass, correct_pass)); printf ("\nOK!"); } //https://pt.stackoverflow.com/q/205228/101
the_stack_data/7951308.c
int function_2() { int a; int b; int c; a = 0; b = c; return b + a; }
the_stack_data/150144393.c
/* * Level_1 Exercise 1.5.1: program to call a function minus(). This function receives two arguments * and returns the difference (regular subtraction, not absolute). This difference should be * printed on screen. * * @file Minus.c * @author Chunyu Yuan * @version 1.0 11/30/2020 * */ // Preprocessor for include file #include <stdio.h> // C tyle I/O // receives two arguments /* * Function to receive two arguments and * return the difference(regular subtraction, not absolute). * * @function minus(float num1, float num2) * @param float num1 // first number * @param float num2 // second number * @return float //the difference(num1-num2) */ float minus(float num1, float num2); /* * Controls operation of the program * Return type of main() expects an int * * @function main() * @param none * @return 0 */ int main() { float num1_input, num2_input; // declare two float numbers: first number, second number float output; //output printf("Please input two numbers to minus: \n\n"); // promote user to input first number printf("The first number: \n"); scanf_s("%f", &num1_input); // promote user to input second number printf("The second number: \n"); scanf_s("%f", &num2_input); //call the minus function to get the subtraction different result output = minus(num1_input, num2_input); //prit result printf("The minus result is %f\n", output); return 0; } // function minus body float minus(float num1, float num2) { return num1 - num2; // regular subtraction }
the_stack_data/14201519.c
#include<stdio.h> int gcd(int x, int y) { if(y == 0) { return x; } else { return gcd(y, x-x/y*y); } return 0; } int main(void) { int a; int b; int c; scanf("%d", &a); scanf("%d", &b); c = gcd(a, b); printf("%d\n", c); return 0; }
the_stack_data/212644394.c
/* PR tree-optimization/59014 */ __attribute__((noinline, noclone)) long long int foo (long long int x, long long int y) { if (((int) x | (int) y) != 0) return 6; return x + y; } int main () { if (sizeof (long long) == sizeof (int)) return 0; int shift_half = sizeof (int) * __CHAR_BIT__ / 2; long long int x = (3LL << shift_half) << shift_half; long long int y = (5LL << shift_half) << shift_half; long long int z = foo (x, y); if (z != ((8LL << shift_half) << shift_half)) __builtin_abort (); return 0; }
the_stack_data/247017406.c
/** Serial communication test program that sends data to the Arduino echo * program and reads the response on UART4. * * Written by Derek Molloy for the book "Exploring BeagleBone: Tools and * Techniques for Building with Embedded Linux" by John Wiley & Sons, 2014 * ISBN 9781118935125. Please see the file README.md in the repository root * directory for copyright and GNU GPLv3 license information. */ #include<stdio.h> #include<fcntl.h> #include<unistd.h> #include<termios.h> // using the termios.h library int main(){ int file, count; if ((file = open("/dev/ttyO4", O_RDWR | O_NOCTTY | O_NDELAY))<0){ perror("UART: Failed to open the file.\n"); return -1; } struct termios options; //The termios structure is vital tcgetattr(file, &options); //Sets the parameters associated with file // Set up the communications options: // 9600 baud, 8-bit, enable receiver, no modem control lines options.c_cflag = B9600 | CS8 | CREAD | CLOCAL; options.c_iflag = IGNPAR | ICRNL; //ignore partity errors, CR -> newline tcflush(file, TCIFLUSH); //discard file information not transmitted tcsetattr(file, TCSANOW, &options); //changes occur immmediately unsigned char transmit[18] = "Hello BeagleBone!"; //the string to send if ((count = write(file, &transmit,18))<0){ //send the string perror("Failed to write to the output\n"); return -1; } usleep(100000); //give the Arduino a chance to respond unsigned char receive[100]; //declare a buffer for receiving data if ((count = read(file, (void*)receive, 100))<0){ //receive the data perror("Failed to read from the input\n"); return -1; } if (count==0) printf("There was no data available to read!\n"); else { printf("The following was read in [%d]: %s\n",count,receive); } close(file); return 0; }
the_stack_data/677907.c
#ifndef lint static char vcid[] = "$Id: getopts.c,v 1.2 1998/04/29 15:15:41 swider Exp $"; #endif /* This file contains routines for processoing options of the form -name <value>. In order to simplify processing by other handlers, the routines eliminate the values from the argument string by compressing it. */ #include <string.h> #include <stdio.h> #include <stdio.h> /* For error handling */ /*@C SYArgSqueeze - Remove all null arguments from an arg vector; update the number of arguments. @*/ void SYArgSqueeze( Argc, argv ) int *Argc; char **argv; { int argc, i, j; /* Compress out the eliminated args */ argc = *Argc; j = 0; i = 0; while (j < argc) { while (argv[j] == 0 && j < argc) j++; if (j < argc) argv[i++] = argv[j++]; } /* Back off the last value if it is null */ if (!argv[i-1]) i--; *Argc = i; } /*@C SYArgFindName - Find a name in an argument list. Input Parameters: + argc - number of arguments . argv - argument vector - name - name to find Returns: index in argv of name; -1 if name is not in argv @*/ int SYArgFindName( argc, argv, name ) int argc; char **argv; char *name; { int i; for (i=0; i<argc; i++) { if (strcmp( argv[i], name ) == 0) return i; } return -1; } /*@C SYArgGetInt - Get the value (integer) of a named parameter. Input Parameters: + Argc - pointer to argument count . argv - argument vector . rflag - if true, remove the argument and its value from argv - val - pointer to value (will be set only if found) Returns: 1 on success Note: This routine handles both decimal and hexidecimal integers. @*/ int SYArgGetInt( Argc, argv, rflag, name, val ) int *Argc, rflag, *val; char **argv, *name; { int idx; char *p; idx = SYArgFindName( *Argc, argv, name ); if (idx < 0) return 0; if (idx + 1 >= *Argc) { fprintf(stderr,"Error: %s\n","Missing value for argument" ); return 0; } p = argv[idx+1]; /* Check for hexidecimal value */ if (((int)strlen(p) > 1) && p[0] == '0' && p[1] == 'x') { sscanf( p, "%i", val ); } else { if ((int)strlen(p) > 1 && p[0] == '-' && p[1] >= 'A' && p[1] <= 'z') { fprintf(stderr,"Error: %s\n","Missing value for argument" ); return 0; } *val = atoi( p ); } if (rflag) { argv[idx] = 0; argv[idx+1] = 0; SYArgSqueeze( Argc, argv ); } return 1; } /*@C SYArgGetDouble - Get the value (double) of a named parameter. Input Parameters: + Argc - pointer to argument count . argv - argument vector . rflag - if true, remove the argument and its value from argv - val - pointer to value (will be set only if found) Returns: 1 on success @*/ int SYArgGetDouble( Argc, argv, rflag, name, val ) int *Argc, rflag; char **argv, *name; double *val; { int idx; extern double atof(); idx = SYArgFindName( *Argc, argv, name ); if (idx < 0) return 0; if (idx + 1 >= *Argc) { fprintf(stderr,"Error: %s\n","Missing value for argument" ); return 0; } *val = atof( argv[idx+1] ); if (rflag) { argv[idx] = 0; argv[idx+1] = 0; SYArgSqueeze( Argc, argv ); } return 1; } /*@C SYArgGetString - Get the value (string) of a named parameter. Input Parameters: + Argc - pointer to argument count . argv - argument vector . rflag - if true, remove the argument and its value from argv . val - pointer to buffer to hold value (will be set only if found). - vallen- length of val Returns: 1 on success @*/ int SYArgGetString( Argc, argv, rflag, name, val, vallen ) int *Argc, rflag, vallen; char **argv, *name, *val; { int idx; idx = SYArgFindName( *Argc, argv, name ); if (idx < 0) return 0; if (idx + 1 >= *Argc) { fprintf(stderr,"Error: %s\n","Missing value for argument" ); return 0; } strncpy( val, argv[idx+1], vallen ); if (rflag) { argv[idx] = 0; argv[idx+1] = 0; SYArgSqueeze( Argc, argv ); } return 1; } /*@C SYArgHasName - Return 1 if name is in argument list Input Parameters: + Argc - pointer to argument count . argv - argument vector . rflag - if true, remove the argument and its value from argv - name - name to search for Returns: 1 on success @*/ int SYArgHasName( Argc, argv, rflag, name ) int *Argc, rflag; char **argv, *name; { int idx; idx = SYArgFindName( *Argc, argv, name ); if (idx < 0) return 0; if (rflag) { argv[idx] = 0; SYArgSqueeze( Argc, argv ); } return 1; } /*@C SYArgGetIntVec - Get the value (integers) of a named parameter. Input Parameters: + Argc - pointer to argument count . argv - argument vector . rflag - if true, remove the argument and its value from argv . n - number of values to read - val - pointer to value (will be set only if found) Note: The form of input is "-name n1 n2 n3 ..." Returns: 1 on success @*/ int SYArgGetIntVec( Argc, argv, rflag, name, n, val ) int *Argc, rflag, *val, n; char **argv, *name; { int idx, i; idx = SYArgFindName( *Argc, argv, name ); if (idx < 0) return 0; /* Fail if there aren't enough values */ if (idx + n + 1 > *Argc) { fprintf(stderr,"Error: %s\n","Not enough values for vector of integers"); return 0; } for (i=0; i<n; i++) { val[i] = atoi( argv[idx+i+1] ); if (rflag) { argv[idx+i+1] = 0; } } if (rflag) { argv[idx] = 0; SYArgSqueeze( Argc, argv ); } return 1; } /*@C SYArgGetIntList - Get the value (integers) of a named parameter. Input Parameters: + Argc - pointer to argument count . argv - argument vector . rflag - if true, remove the argument and its value from argv . n - maximum number of values to read - val - pointer to values (will be set only if found) Note: The form of input is "-name n1,n2,n3 ..." Returns: Number of elements found. 0 if none or error (such as -name with no additional arguments) @*/ int SYArgGetIntList( Argc, argv, rflag, name, n, val ) int *Argc, rflag, *val, n; char **argv, *name; { int idx, i; char *p, *pcomma; idx = SYArgFindName( *Argc, argv, name ); if (idx < 0) return 0; /* Fail if there aren't enough values */ if (idx + 2 > *Argc) { fprintf(stderr,"Error: %s\n","Not enough values for vector of integers"); return 0; } p = argv[idx + 1]; i = 0; while (i + 1 < n && p && *p) { /* Find next comma or end of value */ pcomma = strchr( p, ',' ); if (pcomma) { pcomma[0] = 0; pcomma++; } val[i++] = atoi( p ); p = pcomma; } if (rflag) { argv[idx] = 0; argv[idx+1] = 0; SYArgSqueeze( Argc, argv ); } return i; }
the_stack_data/215766984.c
int ft_is_prime(int nb) { long long i; if (nb <= 1) return (0); if (nb <= 3) return (1); if (!(nb % 2 && nb % 3)) return (0); i = 5; while (i * i <= nb) { if (!(nb % i && nb % (i + 2))) return (0); i += 6; } return (1); } int ft_find_next_prime(int nb) { int i; i = nb; while (!ft_isprime(i)) ++i; return (i); }
the_stack_data/19277.c
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { int x, y; } Pt; typedef struct { int a, b, c; } TwoPt; int cmpPt(const void *u, const void *v) { const Pt *a = u, *b = v; if (a->x != b->x) { return a->x - b->x; } return a->y - b->y; } int cmpTwoPt(const void *a, const void *b) { const TwoPt *x = a, *y = b; if (x->a != y->a) { return x->a - y->a; } if (x->b != y->b) { return x->b - y->b; } if (x->c != y->c) { return x->c - y->c; } return 0; } static inline int gcd(int a, int b) { if (a == b) { return a; } if (a == 0) { return b; } if (b == 0) { return a; } if (a % 2 == 0) { if (b % 2 == 0) { return gcd(a / 2, b / 2) * 2; } else { return gcd(a / 2, b); } } else { if (b % 2 == 0) { return gcd(a, b / 2); } else { if (a > b) { return gcd(a - b, b); } else { return gcd(b - a, a); } } } } static inline int sgn(int x) { return (x > 0) - (x < 0); } static inline int gcd3(int a, int b, int c) { // printf("%d,%d,%d\n", a, b, c); int r = gcd(gcd(abs(a), abs(b)), abs(c)); int sign = sgn(a); if (sign == 0) { sign = sgn(b); } if (sign == 0) { sign = sgn(c); } // printf("%d\n", r); return r * sign; } static inline TwoPt line(Pt d1, Pt d2) { int a = d2.y - d1.y, b = d1.x - d2.x, c = (d2.y - d1.y) * d1.x - (d2.x - d1.x) * d1.y; int g = gcd3(a, b, c); if (g == 0) { g = 1; } TwoPt r = {.a = a / g, .b = b / g, .c = c / g}; return r; } static inline void showTwoPt(TwoPt t) { printf("%dx+%dy=%d\n", t.a, t.b, t.c); } static inline void showPt(Pt t) { printf("%d,%d\n", t.x, t.y); } static inline int deTriNum(int x, int n) { printf("deTriNum %d %d\n", x, n); int b, e, m; for (b = 0, e = n; b <= e;) { m = (b + e) / 2; int t = m * (m - 1) / 2; if (x == t) { return m; } else if (x > t) { b = m + 1; } else { e = m - 1; } } return 0; } /** sort (base, nmemb, size, compar) * map (head &&& length) . group . sort * uniq sorted list, stored in place * length list, stored in new memory */ size_t sortGroupCnt(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *), size_t **opN) { printf("qsort base=%p nmemb=%zu size=%zu compar=%p opN=%p\n", base, nmemb, size, compar, opN); qsort(base, nmemb, size, compar); size_t *cnts = malloc(sizeof(size_t) * nmemb); printf("after qsort\n"); void *last = NULL; size_t i, j, cnt; for (i = j = cnt = 0; i!= nmemb; i++) { if (last != NULL && compar(last, base + i * size) == 0) { cnt++; // same } else { if (last != NULL) { memcpy(base + j * size, last, size), cnts[j] = cnt, j++; } last = base + i * size, cnt = 1; } } if (last != NULL) { memcpy(base + j * size, last, size), cnts[j] = cnt, j++; } if (opN) { *opN = cnts; } else { free(cnts); } return j; } int maxPoints(int **points, int pointsSize, int *pointsColSize) { if (points == NULL || pointsSize <= 1) { return pointsSize; } int nn = (pointsSize) * (pointsSize - 1) / 2; TwoPt *a = malloc(sizeof(TwoPt) * nn); int i, j, k; for (i = k = 0; i != pointsSize; i++) { Pt d1 = {.x = points[i][0], points[i][1]}; for (j = i + 1; j != pointsSize; j++) { Pt d2 = {.x = points[j][0], points[j][1]}; TwoPt r = line(d1, d2); showTwoPt(r); a[k++] = r; } } qsort(a, nn, sizeof(TwoPt), cmpTwoPt); TwoPt last = a[0]; int mcnt = 1, cnt = 1; for (k = 1; k != nn; k++) { if (cmpTwoPt(&a[k], &last) == 0) { cnt++; if (cnt > mcnt) { mcnt = cnt; } } else { printf("cnt=%d\n", cnt); last = a[k]; showTwoPt(last); cnt = 1; } } printf("%d\n", mcnt); int ret = deTriNum(mcnt, pointsSize); printf("%d\n", ret); free(a); return ret; } int unit0() { int pts[][2] = {{1, 1}, {3, 2}, {5, 3}, {4, 1}, {2, 3}, {1, 4}}; int *points[] = {pts[0], pts[1], pts[2], pts[3], pts[4], pts[5]}; int size = 0; int r = maxPoints(points, sizeof(points) / sizeof(points[0]), &size); printf("r=%d\n", r); return 0; } int unit1() { // int pts[][2] = {{1, 1}, {2,2 }, {3, 3}}; // int *points[] = {pts[0], pts[1], pts[2]}; // int pts[][2] = {{1, 1}, {2,2 }}; // int *points[] = {pts[0], pts[1]}; // int pts[][2] = {{1, 1}}; // int *points[] = {pts[0]}; // int pts[][2] = {{1, 1}, {1, 1}}; // int *points[] = {pts[0], pts[1]}; // int pts[][2] = {{1, 1}, {1,1 }, {1, 1}}; // int *points[] = {pts[0], pts[1], pts[2]}; // int pts[][2] = {{0, 0}, {1,1 }, {1, 1}}; // int *points[] = {pts[0], pts[1], pts[2]}; int pts[][2] = {{2, 2}, {1,1 }, {1, 1}}; int *points[] = {pts[0], pts[1], pts[2]}; int size = 0; int r = maxPoints(points, sizeof(points) / sizeof(points[0]), &size); printf("r=%d\n", r); return 0; } int unit2() { // int pts[][2] = {}; // int pts[][2] = {{1,1 }}; // int pts[][2] = {{1, 1}, {1,1 }}; // int pts[][2] = {{2, 2}, {1,1 }}; int pts[][2] = {{2, 2}, {1,1 }, {1, 1}}; size_t *pn = NULL; size_t n = sortGroupCnt(pts, sizeof(pts) / sizeof(pts[0]), sizeof(pts[0]), cmpPt, &pn); size_t i; for (i = 0; i != n; i++) { printf("%d,%d\n", pts[i][0], pts[i][1]); if (pn != NULL) { printf("%zu\n", pn[i]); } } if (pn != NULL) { free(pn); } return 0; } int main() { // unit0(); // unit1(); unit2(); return 0; }
the_stack_data/498317.c
#include <math.h> float erfcc(float x) { float t,z,ans; z=fabs(x); t=1.0/(1.0+0.5*z); ans=t*exp(-z*z-1.26551223+t*(1.00002368+t*(0.37409196+t*(0.09678418+ t*(-0.18628806+t*(0.27886807+t*(-1.13520398+t*(1.48851587+ t*(-0.82215223+t*0.17087277))))))))); return x >= 0.0 ? ans : 2.0-ans; } /* (C) Copr. 1986-92 Numerical Recipes Software 7&X*. */
the_stack_data/136080.c
/***************************************************************************** * websocket_chat.c: Simple Chat server ***************************************************************************** * Copyright (C) 2016-2017 * * Authors: Marc Chalain <[email protected] * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject * to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL 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. *****************************************************************************/ #include <stdio.h> #define __USE_GNU #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <pwd.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/select.h> #include <sys/un.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sched.h> #include <sys/stat.h> #include <libgen.h> #define err(format, ...) fprintf(stderr, "\x1B[31m"format"\x1B[0m\n", ##__VA_ARGS__) #define warn(format, ...) fprintf(stderr, "\x1B[35m"format"\x1B[0m\n", ##__VA_ARGS__) #ifdef DEBUG #define dbg(format, ...) fprintf(stderr, "\x1B[32m"format"\x1B[0m\n", ##__VA_ARGS__) #else #define dbg(...) #endif typedef int (*server_t)(int sock); typedef struct identity_s identity_t; struct identity_s { char name[30]; }; typedef struct user_s user_t; struct user_s { int sock; identity_t *identity; user_t *next; user_t *prev; }; #define WS_MSG 0x01 #define DAEMON 0x02 static user_t *first_user = NULL; int chatmsg(user_t *user, char *buffer, int length) { int ret = 0; user_t *iterator = first_user; while (iterator) { if (iterator->sock != user->sock) { send(iterator->sock, buffer, length, MSG_DONTWAIT); dbg("send to %d : %s", iterator->sock, buffer); } iterator = iterator->next; } return ret; } int privatemsg(user_t *dest, char *buffer, int length) { int ret = 0; user_t *iterator = first_user; while (iterator) { if (iterator->sock == dest->sock) { send(iterator->sock, buffer, length, MSG_DONTWAIT); dbg("send to %d : %s", iterator->sock, buffer); } iterator = iterator->next; } return ret; } int chat(user_t *user, char *buffer, int length) { int ret = 0; if (!strncmp(buffer,"WSHello ", 8)) { char *identity = buffer + 8; buffer += 8; length = 0; while ((*buffer != '\n') && (*buffer != ' ') && (*buffer != '\0')) { buffer++; length++; } if (length > 0) { *buffer = 0; int i = 0; user_t *iterator = first_user; while (iterator) { if (!strncmp(iterator->identity->name, identity, 30)) { i++; } iterator = iterator->next; } strncpy(user->identity->name, identity, sizeof(user->identity->name)); if (i > 0) { if (length > 27) length = 27; sprintf(user->identity->name + length, "%03hd", i); } char resp[40]; sprintf(resp, "WSWelcome %s", user->identity->name); privatemsg(user, resp, strlen(resp)); } } else if (!strncmp(buffer,"WSPrivate ", 10)) { char *identity = buffer + 10; buffer += 10; length -= 10; while ((*buffer != '\n') && (*buffer != ' ') && (length > 0)) { buffer++; length--; } if (length > 0) { *buffer = 0; buffer++; length--; user_t *iterator = first_user; while (iterator) { if (!strncmp(iterator->identity->name, identity, 30)) ret = privatemsg(iterator, buffer, length); iterator = iterator->next; } } } else if (!strncmp(buffer,"WSWhois ", 8)) { char *identity = buffer + 8; buffer += 8; length = 0; while ((*buffer != '\n') && (*buffer != ' ') && (*buffer != '\0')) { buffer++; length++; } if (length > 0) { *buffer = 0; int i = 0; user_t *iterator = first_user; while (iterator) { if (!strncmp(iterator->identity->name, identity, 30)) { break; } iterator = iterator->next; } char resp[52]; struct sockaddr_storage addr; int addrsize = sizeof(addr); if (iterator) { getpeername(iterator->sock, (struct sockaddr*)&addr, &addrsize); if (addr.ss_family == AF_INET) { struct sockaddr_in *addr_in = (struct sockaddr_in *)&addr; sprintf(resp, "WSIs %s %s", identity, inet_ntoa(addr_in->sin_addr)); } else sprintf(resp, "WSIs %s network error", identity); } else sprintf(resp, "WSIs %s undefined", identity); privatemsg(user, resp, strlen(resp)); } } else ret = chatmsg(user, buffer, length); return ret; } void help(char **argv) { fprintf(stderr, "%s [-R <socket directory>][-m <nb max clients>][-u <user>][-w][-h][-D]\n", basename(argv[0])); fprintf(stderr, "\t-R <dir>\tset the socket directory for the connection (default: /var/run/websocket)\n"); fprintf(stderr, "\t-n <name>\tset the protocol (default: %s)\n", basename(argv[0])); fprintf(stderr, "\t-m <num>\tset the maximum number of clients (default: 50)\n"); fprintf(stderr, "\t-u <name>\tset the user to run (default: current)\n"); fprintf(stderr, "\t-w \tstart chat with specific ouistiti features\n"); fprintf(stderr, "\t-D \tdaemonize the server\n"); } static const char *str_hello = "{\"type\":\"hello\",\"data\":\"%2hd\"}"; #ifndef SOCKDOMAIN #define SOCKDOMAIN AF_UNIX #endif #ifndef SOCKPROTOCOL #define SOCKPROTOCOL 0 #endif int main(int argc, char **argv) { int ret = -1; int sock; char *root = "/var/run/websocket"; char *proto = basename(argv[0]); int maxclients = 50; const char *username = NULL; int options = 0; int opt; do { opt = getopt(argc, argv, "u:n:R:m:wDh"); switch (opt) { case 'R': root = optarg; break; case 'h': help(argv); return -1; case 'm': maxclients = atoi(optarg); break; case 'u': username = optarg; break; case 'n': proto = optarg; break; case 'w': options |= WS_MSG; break; case 'D': options |= DAEMON; break; } } while(opt != -1); if (access(root, R_OK|W_OK|X_OK)) { if (mkdir(root, 0777)) { err("access %s error %s", root, strerror(errno)); return -1; } chmod(root, 0777); } if (getuid() == 0 && username != NULL) { struct passwd *user = NULL; user = getpwnam(username); if (user != NULL) { if (setegid(user->pw_gid) < 0) warn("not enought rights to change group"); if (seteuid(user->pw_uid) < 0) warn("not enought rights to change user"); } else warn("user not found"); } sock = socket(SOCKDOMAIN, SOCK_STREAM, SOCKPROTOCOL); if (sock > 0) { struct sockaddr_un addr; memset(&addr, 0, sizeof(struct sockaddr_un)); addr.sun_family = AF_UNIX; snprintf(addr.sun_path, sizeof(addr.sun_path) - 1, "%s/%s", root, proto); unlink(addr.sun_path); ret = bind(sock, (struct sockaddr *) &addr, sizeof(addr)); if (ret == 0) { chmod(addr.sun_path, 0777); ret = listen(sock, maxclients); } if ((options & DAEMON) && (fork() != 0)) { printf("chat: daemonize\n"); sched_yield(); return 0; } if (ret == 0) { int newsock = -1; do { fd_set rfds; int maxfd = sock; FD_ZERO(&rfds); FD_SET(sock, &rfds); user_t *user = first_user; while (user) { FD_SET(user->sock, &rfds); maxfd = (maxfd < user->sock)?user->sock:maxfd; user = user->next; } ret = select(maxfd + 1, &rfds, NULL, NULL, NULL); if (ret > 0) { if (FD_ISSET(sock, &rfds)) { struct sockaddr_storage addr; int addrsize = sizeof(addr); newsock = accept(sock, (struct sockaddr *)&addr, &addrsize); if (newsock > 0) { user_t *user = calloc(1, sizeof(*user)); user->identity = calloc(1, sizeof(*(user->identity))); user->sock = newsock; user->next = first_user; if (first_user) first_user->prev = user; first_user = user; if (addr.ss_family == AF_INET) { struct sockaddr_in *addr_in = (struct sockaddr_in *)&addr; warn("chat: new connection from %s %p", inet_ntoa(addr_in->sin_addr), user); } else warn("chat: new connection"); /* char *buffer = calloc(1, strlen(str_hello) + 1); sprintf(buffer, str_hello, newsock); privatemsg(user, buffer, strlen(buffer)); free(buffer); */ } } user_t *user = first_user; while (user) { if (FD_ISSET(user->sock, &rfds)) { char buffer[512]; int length = 512; length = read(user->sock, buffer, length); if ((length <= 0) && (errno != EAGAIN)) { warn("chat: goodbye %p", user); if (user->prev) { user->prev->next = user->next; } else first_user = user->next; if (user->next) user->next->prev = user->prev; close(user->sock); if (user->identity) free(user->identity); free(user); break; } else if (length > 0) { dbg("chat: receive from %d : %s", user->sock, buffer); if (options & WS_MSG) chat(user, buffer, length); else chatmsg(user, buffer, length); } } user = user->next; } } } while(newsock > 0); } unlink(addr.sun_path); } if (ret) { err("chat: error %s\n", strerror(errno)); } return ret; }
the_stack_data/556162.c
#include<stdio.h> int main() { int a=2; int b=2; if(a==1) { if(b==2) printf("a was 1 and b was 2\n"); } else printf("a wasn't 1\n"); return 0; }
the_stack_data/14200691.c
#include <stdlib.h> #include <string.h> #include <assert.h> extern int doMainCTE (int argc, char **argv); int main (int argc, char **argv) { // alloc a new argv + 1 for the above new option char ** newArgv = malloc((argc + 1)*sizeof(char*)); assert(newArgv); // Copy the old pointers to the new one memcpy(newArgv, argv, argc*sizeof(char*)); // Add the new opt and inc argc newArgv[argc++] = "--forwardModelOnly"; const int status = doMainCTE(argc, newArgv); free(newArgv); return status; }
the_stack_data/248579708.c
#include "stdio.h" #include "stdlib.h" #include "math.h" #include "time.h" #define OK 1 #define ERROR 0 #define TRUE 1 #define FALSE 0 #define MAXSIZE 100 /* 存储空间初始分配量 */ typedef int Status; /* Status是函数的类型,其值是函数结果状态代码,如OK等 */ /* 二叉树的二叉链表结点结构定义 */ typedef struct BiTNode /* 结点结构 */ { int data; /* 结点数据 */ int bf; /* 结点的平衡因子 */ struct BiTNode *lchild, *rchild; /* 左右孩子指针 */ } BiTNode, *BiTree; /* 对以p为根的二叉排序树作右旋处理, */ /* 处理之后p指向新的树根结点,即旋转处理之前的左子树的根结点 */ void R_Rotate(BiTree *P) { BiTree L; L=(*P)->lchild; /* L指向P的左子树根结点 */ (*P)->lchild=L->rchild; /* L的右子树挂接为P的左子树 */ L->rchild=(*P); *P=L; /* P指向新的根结点 */ } /* 对以P为根的二叉排序树作左旋处理, */ /* 处理之后P指向新的树根结点,即旋转处理之前的右子树的根结点0 */ void L_Rotate(BiTree *P) { BiTree R; R=(*P)->rchild; /* R指向P的右子树根结点 */ (*P)->rchild=R->lchild; /* R的左子树挂接为P的右子树 */ R->lchild=(*P); *P=R; /* P指向新的根结点 */ } #define LH +1 /* 左高 */ #define EH 0 /* 等高 */ #define RH -1 /* 右高 */ /* 对以指针T所指结点为根的二叉树作左平衡旋转处理 */ /* 本算法结束时,指针T指向新的根结点 */ void LeftBalance(BiTree *T) { BiTree L,Lr; L=(*T)->lchild; /* L指向T的左子树根结点 */ switch(L->bf) { /* 检查T的左子树的平衡度,并作相应平衡处理 */ case LH: /* 新结点插入在T的左孩子的左子树上,要作单右旋处理 */ (*T)->bf=L->bf=EH; R_Rotate(T); break; case RH: /* 新结点插入在T的左孩子的右子树上,要作双旋处理 */ Lr=L->rchild; /* Lr指向T的左孩子的右子树根 */ switch(Lr->bf) { /* 修改T及其左孩子的平衡因子 */ case LH: (*T)->bf=RH; L->bf=EH; break; case EH: (*T)->bf=L->bf=EH; break; case RH: (*T)->bf=EH; L->bf=LH; break; } Lr->bf=EH; L_Rotate(&(*T)->lchild); /* 对T的左子树作左旋平衡处理 */ R_Rotate(T); /* 对T作右旋平衡处理 */ } } /* 对以指针T所指结点为根的二叉树作右平衡旋转处理, */ /* 本算法结束时,指针T指向新的根结点 */ void RightBalance(BiTree *T) { BiTree R,Rl; R=(*T)->rchild; /* R指向T的右子树根结点 */ switch(R->bf) { /* 检查T的右子树的平衡度,并作相应平衡处理 */ case RH: /* 新结点插入在T的右孩子的右子树上,要作单左旋处理 */ (*T)->bf=R->bf=EH; L_Rotate(T); break; case LH: /* 新结点插入在T的右孩子的左子树上,要作双旋处理 */ Rl=R->lchild; /* Rl指向T的右孩子的左子树根 */ switch(Rl->bf) { /* 修改T及其右孩子的平衡因子 */ case RH: (*T)->bf=LH; R->bf=EH; break; case EH: (*T)->bf=R->bf=EH; break; case LH: (*T)->bf=EH; R->bf=RH; break; } Rl->bf=EH; R_Rotate(&(*T)->rchild); /* 对T的右子树作右旋平衡处理 */ L_Rotate(T); /* 对T作左旋平衡处理 */ } } /* 若在平衡的二叉排序树T中不存在和e有相同关键字的结点,则插入一个 */ /* 数据元素为e的新结点,并返回1,否则返回0。若因插入而使二叉排序树 */ /* 失去平衡,则作平衡旋转处理,布尔变量taller反映T长高与否。 */ Status InsertAVL(BiTree *T,int e,Status *taller) { if(!*T) { /* 插入新结点,树“长高”,置taller为TRUE */ *T=(BiTree)malloc(sizeof(BiTNode)); (*T)->data=e; (*T)->lchild=(*T)->rchild=NULL; (*T)->bf=EH; *taller=TRUE; } else { if (e==(*T)->data) { /* 树中已存在和e有相同关键字的结点则不再插入 */ *taller=FALSE; return FALSE; } if (e<(*T)->data) { /* 应继续在T的左子树中进行搜索 */ if(!InsertAVL(&(*T)->lchild,e,taller)) /* 未插入 */ return FALSE; if(*taller) /* 已插入到T的左子树中且左子树“长高” */ switch((*T)->bf) /* 检查T的平衡度 */ { case LH: /* 原本左子树比右子树高,需要作左平衡处理 */ LeftBalance(T); *taller=FALSE; break; case EH: /* 原本左、右子树等高,现因左子树增高而使树增高 */ (*T)->bf=LH; *taller=TRUE; break; case RH: /* 原本右子树比左子树高,现左、右子树等高 */ (*T)->bf=EH; *taller=FALSE; break; } } else { /* 应继续在T的右子树中进行搜索 */ if(!InsertAVL(&(*T)->rchild,e,taller)) /* 未插入 */ return FALSE; if(*taller) /* 已插入到T的右子树且右子树“长高” */ switch((*T)->bf) /* 检查T的平衡度 */ { case LH: /* 原本左子树比右子树高,现左、右子树等高 */ (*T)->bf=EH; *taller=FALSE; break; case EH: /* 原本左、右子树等高,现因右子树增高而使树增高 */ (*T)->bf=RH; *taller=TRUE; break; case RH: /* 原本右子树比左子树高,需要作右平衡处理 */ RightBalance(T); *taller=FALSE; break; } } } return TRUE; } int main(void) { int i; int a[10]={3,2,1,4,5,6,7,10,9,8}; BiTree T=NULL; Status taller; for(i=0;i<10;i++) { InsertAVL(&T,a[i],&taller); } printf("本样例建议断点跟踪查看平衡二叉树结构"); return 0; }
the_stack_data/28263545.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <dirent.h> #include <unistd.h> #include <time.h> #include <fcntl.h> #include <error.h> #include <grp.h> #include <grp.h> #include <pwd.h> #include <linux/limits.h> void print_filename(char *filename, char *filepath); void display_attribute(struct stat buf); void file_information(char *filename); void bianli_dir(char *dirname); void bianli_dir_easy(char *dirname); void bianli_dir_l(char *dirnamr); void bianli_dir_easy_a(char *dirname); void bianli_dir_al(char *dirname); void bianli_dir_R(char *dirname); void bianli_dir_lR(char *dirname); void bianli_dir_aR(char *dirname); void bianli_dir_easy_a2(char *dirname); int main(int argc, char *argv[]) { char path[4096]; int num = 0; int i; for(i=0; i<argc; i++){ if(argv[i][0] == '-') num++; } if(num == 0){ if(argc == 1){ bianli_dir_easy("."); } else{ strcpy(path, argv[1]); bianli_dir_easy(path); } } else{ char *option = argv[1]; if(strcmp(option, "-r") == 0){ //-r命令 if(argc == 2){ bianli_dir("."); } else{ strcpy(path, argv[2]); bianli_dir(path); } } else if(strcmp(option, "-l") == 0){ //-l命令 if(argc == 2){ bianli_dir_l("."); } else{ strcpy(path, argv[2]); bianli_dir_l(path); } } else if(strcmp(option, "-a") == 0){ if(argc == 2){ bianli_dir_easy_a2("."); } else{ strcpy(path, argv[2]); bianli_dir_easy_a2(path); } } else if(strcmp(option, "-al") == 0 || strcmp(option, "-la") == 0){ if(argc == 2){ bianli_dir_al("."); } else{ strcpy(path, argv[2]); bianli_dir_al(path); } } else if(strcmp(option, "-R") == 0){ if(argc == 2){ bianli_dir_R("."); } else{ strcpy(path, argv[2]); bianli_dir_R(path); } } else if(strcmp(option, "-lR") == 0 || strcmp(option, "-Rl") == 0){ if(argc == 2){ bianli_dir_lR("."); } else{ strcpy(path, argv[2]); bianli_dir_lR(path); } } else if(strcmp(option, "-aR") == 0 || strcmp(option, "-lR") == 0){ if(argc == 2){ bianli_dir_aR("."); } else{ strcpy(path, argv[2]); bianli_dir_aR(path); } } } return 0; } //打印文件名,不同类型不同的显示 void print_filename(char *filename, char *filepath){ struct stat buf; stat(filepath, &buf); if(S_ISREG(buf.st_mode)){ if(buf.st_mode & S_IXUSR){ printf("\033[1;32m%s\033[0m\n", filename); } else{ printf("%s\n", filename); } } else if(S_ISDIR(buf.st_mode)){ printf("\033[1;34m%s\033[0m\n", filename); } else if(S_ISLNK(buf.st_mode)){ printf("\033[1;31m%s\033[0m\n", filename); } } //获取显示文件信息并打印 void display_attribute(struct stat buf){ char buf_time[32]; struct passwd *psd; struct group *grp; //文件类型 char file_type[11]; if(S_ISLNK(buf.st_mode)){ file_type[0] = 'l'; } else if(S_ISREG(buf.st_mode)){ file_type[0] = '-'; } else if(S_ISDIR(buf.st_mode)){ file_type[0] = 'd'; } //所有者权限 if(buf.st_mode & S_IRUSR){ file_type[1] = 'r'; } else{ file_type[1] = '-'; } if(buf.st_mode & S_IWUSR){ file_type[2] = 'w'; } else{ file_type[2] = '-'; } if(buf.st_mode & S_IXUSR){ file_type[3] = 'x'; } else{ file_type[3] = '-'; } //所属组权限 if(buf.st_mode & S_IRGRP){ file_type[4] = 'r'; } else{ file_type[4] = '-'; } if(buf.st_mode & S_IWGRP){ file_type[5] = 'w'; } else{ file_type[5] = '-'; } if(buf.st_mode & S_IXGRP){ file_type[6] = 'x'; } else{ file_type[6] = '-'; } //其他用户权限 if(buf.st_mode & S_IROTH){ file_type[7] = 'r'; } else{ file_type[7] = '-'; } if(buf.st_mode & S_IWOTH){ file_type[8] = 'w'; } else{ file_type[8] = '-'; } if(buf.st_mode & S_IXOTH){ file_type[9] = 'x'; } else{ file_type[9] = '-'; } file_type[10] = '\0'; printf("%s ", file_type); //获取文件所有者的用户名组名 psd = getpwuid(buf.st_uid); grp = getgrgid(buf.st_uid); printf("%ld\t", buf.st_nlink); printf("%s\t", psd->pw_name); printf("%s\t", grp->gr_name); printf("%6ld\t", buf.st_size); strcpy(buf_time, ctime(&buf.st_mtime)); buf_time[strlen(buf_time) - 1] = '\0'; printf("%s ", buf_time); } //显示文件信息 void file_information(char *filename){ int fd; char buf[4096]; fd = open(filename, O_RDONLY); if(fd == -1){ printf("line:%d\n", __LINE__-2); perror("open"); } struct stat file_stat; stat(filename, &file_stat); display_attribute(file_stat); //printf("%s\n", filename); close(fd); } //-r命令 void bianli_dir(char *dirname){ char filepath[4096]; DIR *dir = opendir(dirname); struct dirent *dir_struct = readdir(dir); while(dir_struct){ sprintf(filepath, "%s/%s", dirname, dir_struct->d_name); if(dir_struct->d_type == DT_REG){ file_information(filepath); print_filename(dir_struct->d_name, filepath); } else if(dir_struct->d_type == DT_DIR){ if(strcmp(dir_struct->d_name, ".") == 0 || strcmp(dir_struct->d_name, "..") == 0){ dir_struct = readdir(dir); continue; } file_information(filepath); //printf("%s\n", dir_struct->d_name); print_filename(dir_struct->d_name, filepath); bianli_dir(filepath); } dir_struct = readdir(dir); } closedir(dir); } //-R命令 void bianli_dir_R(char *dirname){ char filepath[4096]; //DIR *dir = opendir(dirname); DIR *dir; //struct dirent *dir_struct = readdir(dir); struct dirent *dir_struct; char **dirlist; int tmp = 0; char temp[1024]; struct stat buf; //统计目录下文件的数量 dir = opendir(dirname); if(dir == NULL){ printf("line: %d", __LINE__-2); perror("opendir"); exit(1); } while((dir_struct = readdir(dir)) != NULL){ tmp++; } closedir(dir); //开辟dirlist空间,用来储存目录下的目录文件 dirlist = (char**)malloc(sizeof(char*)*tmp); for(int i=0; i<tmp; i++){ dirlist[i] = (char*)malloc(sizeof(char)*1024); } //初始化dirlist for(int i=0; i<tmp; i++){ for(int j=0; j<1024; j++){ dirlist[i][j] = '\0'; } } //将目录属性的文件写入dirlist int k = 0; dir = opendir(dirname); dir_struct = readdir(dir); sprintf(filepath, "%s/%s", dirname, dir_struct->d_name); //printf("tmp = %d\n", tmp); for(int i=0; i<tmp; i++){ //dir_struct = readdir(dir); if(dir_struct == NULL){ printf("line:%d ", __LINE__-2); perror("readdir"); } int ret = stat(filepath, &buf); if(ret == -1){ printf("line:%d ", __LINE__-2); perror("stat"); exit(1); } //printf("a:%s\n", filepath); if(S_ISDIR(buf.st_mode)){ strcpy(dirlist[k], filepath); dirlist[k][strlen(filepath)] = '\0'; //printf("%s\n", dirlist[k]); //dir_struct = readdir(dir); memset(filepath, 0, 4096); sprintf(filepath, "%s/%s", dirname, dir_struct->d_name); //printf("k = %d\n", k); k++; } else{ //printf("b\n"); //dir_struct = readdir(dir); memset(filepath, 0, 4096); sprintf(filepath, "%s/%s", dirname, dir_struct->d_name); } dir_struct = readdir(dir); } closedir(dir); //对dirlist排序 for(int i=0; i<k; i++){ for(int j=0; j<k-i-1; j++){ if(strcmp(dirlist[j], dirlist[j+1]) > 0){ strcpy(temp, dirlist[j+1]); temp[strlen(dirlist[j+1])] = '\0'; strcpy(dirlist[j+1], dirlist[j]); dirlist[j+1][strlen(dirlist[j])] = '\0'; strcpy(dirlist[j], temp); dirlist[j][strlen(temp)] = '\0'; } } } //printf("k = %d\n", k); /*for(int i=0; i<k; i++){ printf("%s\n", dirlist[i]); } printf("------------");*/ int i=0; while(i < k){ if(strcmp(dirlist[i], "..") == 0){ i++; continue; } else{ printf("%s:\n", dirlist[i]); bianli_dir_easy(dirlist[i]); //printf("\n"); } i++; } } //-lR选项 void bianli_dir_lR(char *dirname){ char filepath[4096]; DIR *dir = opendir(dirname); struct dirent *dir_struct = readdir(dir); while(dir_struct){ //printf("a\n"); sprintf(filepath, "%s/%s", dirname, dir_struct->d_name); //printf("%s\n", filepath); if(dir_struct->d_type == DT_REG){ dir_struct = readdir(dir); continue; } else if(dir_struct->d_type == DT_DIR){ if(strcmp(dir_struct->d_name, "..") == 0){ dir_struct = readdir(dir); continue; } else if(strcmp(dir_struct->d_name, ".") == 0){ printf(".:\n"); bianli_dir_l(filepath); } else{ printf("%s:\n", filepath); bianli_dir_l(filepath); } } dir_struct = readdir(dir); } closedir(dir); } //只有ls命令,限时所有文件 void bianli_dir_easy_a2(char *dirname){ char filepath[4096]; struct stat buf; char **filelist; //DIR *dir = opendir(dirname); //struct dirent *dir_struct = readdir(dir); int tmp; stat(dirname, &buf); //printf("b\n"); if(S_ISREG(buf.st_mode)){ printf("a\n"); if(buf.st_mode & S_IXUSR){ //file_information(dirname); printf("\033[1;32m %s\033[0m\n", dirname); } else{ //file_information(dirname); printf("%s\n", dirname); } } else{ tmp = 0; //DIR *dir = opendir(dirname); DIR *dir; //struct dirent *dir_struct = readdir(dir); struct dirent *dir_struct; char temp[1024]; //统计目录下文件的数量 dir = opendir(dirname); if(dir == NULL){ printf("line: %d\n", __LINE__-2); perror("opendir"); exit(1); } dir_struct = readdir(dir); while(dir_struct != NULL){ tmp++; dir_struct = readdir(dir); } closedir(dir); //printf("tmp = %d\n", tmp); //malloc空间,字符串数组 /*for(int i=0; i<tmp; i++){ filelist[i] = (char*)malloc(sizeof(char)*1024); }*/ //malloc空间,字符串数组 filelist = (char**)malloc(sizeof(char*)*tmp); for(int i=0; i<tmp; i++){ filelist[i] = (char*)malloc(sizeof(char)*1024); } //printf("a\n"); //将目录下的文件名写入filelist dir = opendir(dirname); for(int i=0; i<tmp; i++){ //printf("a\n"); dir_struct = readdir(dir); if(dir_struct == NULL){ printf("line: %d\n", __LINE__-2); perror("opendir"); } //sprintf(filepath, "%s/%s", dirname, dir_struct->d_name); strcpy(filelist[i], dir_struct->d_name); filelist[i][strlen(dir_struct->d_name)] = '\0'; //printf("%s\n", filelist[i]); } closedir(dir); //对文件名进行排序 for(int i=0; i<tmp; i++){ for(int j=0; j<tmp-i-1; j++){ if(strcmp(filelist[j], filelist[j+1]) > 0){ strcpy(temp, filelist[j+1]); temp[strlen(filelist[j+1])] = '\0'; strcpy(filelist[j+1], filelist[j]); filelist[j+1][strlen(filelist[j])] = '\0'; strcpy(filelist[j], temp); filelist[j][strlen(temp)] = '\0'; } } } filelist[tmp] = NULL; //输出文件 for(int i=0; i<tmp; i++){ printf("%-10s ", filelist[i]); if((i+1)%5 == 0){ printf("\n"); } } printf("\n"); //释放filelist空间 /*for(int i=0; i<tmp; i++){ free(*(filelist+i)); }*/ /* while(dir_struct){ sprintf(filepath, "%s/%s", dirname, dir_struct->d_name); if(strcmp(dir_struct->d_name, ".") == 0 || strcmp(dir_struct->d_name, "..") == 0){ dir_struct = readdir(dir); continue; } stat(filepath, &buf); if(S_ISREG(buf.st_mode)){ if(buf.st_mode & S_IXUSR){ printf("\033[1;32m %s\033[0m\t", dir_struct->d_name); } else{ printf("%s\t", dir_struct->d_name); } } else if(S_ISDIR(buf.st_mode)){ printf("\033[1;34m %s\033[0m\t", dir_struct->d_name); } dir_struct = readdir(dir); } */ //printf("\n"); //closedir(dir); } } //只有ls命令,显示当前目录的文件,不包括隐藏文件 void bianli_dir_easy(char *dirname){ char filepath[4096]; struct stat buf; char **filelist; //DIR *dir = opendir(dirname); //struct dirent *dir_struct = readdir(dir); int tmp; stat(dirname, &buf); //printf("b\n"); if(S_ISREG(buf.st_mode)){ printf("a\n"); if(buf.st_mode & S_IXUSR){ //file_information(dirname); printf("\033[1;32m %s\033[0m\n", dirname); } else{ //file_information(dirname); printf("%s\n", dirname); } } else{ tmp = 0; //DIR *dir = opendir(dirname); DIR *dir; //struct dirent *dir_struct = readdir(dir); struct dirent *dir_struct; char temp[1024]; //统计目录下文件的数量 //printf("%s\n", dirname); dir = opendir(dirname); if(dir == NULL){ printf("line: %d\n", __LINE__-2); perror("opendir"); exit(1); } dir_struct = readdir(dir); while(dir_struct != NULL){ tmp++; dir_struct = readdir(dir); } closedir(dir); //printf("a\n"); //malloc空间,字符串数组 /*for(int i=0; i<tmp; i++){ filelist[i] = (char*)malloc(sizeof(char)*1024); }*/ //malloc空间,字符串数组 filelist = (char**)malloc(sizeof(char*)*tmp); for(int i=0; i<tmp; i++){ filelist[i] = (char*)malloc(sizeof(char)*1024); } //printf("a\n"); //将目录下的文件名写入filelist dir = opendir(dirname); for(int i=0; i<tmp; i++){ //printf("a\n"); dir_struct = readdir(dir); if(dir_struct == NULL){ printf("line: %d\n", __LINE__-2); perror("opendir"); } strcpy(filelist[i], dir_struct->d_name); filelist[i][strlen(dir_struct->d_name)] = '\0'; //printf("%s\n", filelist[i]); } closedir(dir); //对文件名进行排序 for(int i=0; i<tmp; i++){ for(int j=0; j<tmp-i-1; j++){ if(strcmp(filelist[j], filelist[j+1]) > 0){ strcpy(temp, filelist[j+1]); temp[strlen(filelist[j+1])] = '\0'; strcpy(filelist[j+1], filelist[j]); filelist[j+1][strlen(filelist[j])] = '\0'; strcpy(filelist[j], temp); filelist[j][strlen(temp)] = '\0'; } } } filelist[tmp] = NULL; //输出文件 for(int i=0; i<tmp; i++){ if(filelist[i][0] == '.'){ continue; } printf("%-12s", filelist[i]); if(i%5 == 0){ printf("\n"); } } printf("\n"); //释放filelist空间 /*for(int i=0; i<tmp; i++){ free(*(filelist+i)); }*/ /* while(dir_struct){ sprintf(filepath, "%s/%s", dirname, dir_struct->d_name); if(strcmp(dir_struct->d_name, ".") == 0 || strcmp(dir_struct->d_name, "..") == 0){ dir_struct = readdir(dir); continue; } stat(filepath, &buf); if(S_ISREG(buf.st_mode)){ if(buf.st_mode & S_IXUSR){ printf("\033[1;32m %s\033[0m\t", dir_struct->d_name); } else{ printf("%s\t", dir_struct->d_name); } } else if(S_ISDIR(buf.st_mode)){ printf("\033[1;34m %s\033[0m\t", dir_struct->d_name); } dir_struct = readdir(dir); } */ //printf("\n"); //closedir(dir); } } //-a,显示当前目录的文件,包括隐藏文件 void bianli_dir_easy_a(char *dirname){ char filepath[4096]; struct stat buf; //DIR *dir = opendir(dirname); //struct dirent *dir_struct = readdir(dir); stat(dirname, &buf); if(S_ISREG(buf.st_mode)){ if(buf.st_mode & S_IXUSR){ printf("\033[1;32m%s\033[0m\n", dirname); } else{ printf("%s\n", dirname); } } else{ DIR *dir = opendir(dirname); struct dirent *dir_struct = readdir(dir); while(dir_struct){ sprintf(filepath, "%s/%s", dirname, dir_struct->d_name); stat(filepath, &buf); if(S_ISREG(buf.st_mode)){ if(buf.st_mode & S_IXUSR){ //printf("\033[1;32m%s\033[0m\t", dir_struct->d_name); printf("\033[1;32m%s\033[0m\t", dir_struct->d_name); } else{ printf("%s\t", dir_struct->d_name); } } else if(S_ISDIR(buf.st_mode)){ printf("\033[1;34m%s\033[m\t", dir_struct->d_name); } dir_struct = readdir(dir); } printf("\n"); closedir(dir); } } //-l命令,显示dirname的信息 void bianli_dir_l(char *dirname){ //DIR *dir = opendir(dirname); //struct dirent *dir_struct = readdir(dir); char filepath[4096]; struct stat buf; stat(dirname, &buf); if(S_ISREG(buf.st_mode)){ if(S_IXUSR & buf.st_mode){ file_information(dirname); printf("\033[1;32m%s\033[0m\n", dirname); } else{ file_information(dirname); printf("%s\n", dirname); } } else{ DIR *dir = opendir(dirname); struct dirent *dir_struct = readdir(dir); while(dir_struct){ sprintf(filepath, "%s/%s", dirname, dir_struct->d_name); if(strcmp(dir_struct->d_name, ".") == 0 || strcmp(dir_struct->d_name, "..") == 0){ dir_struct = readdir(dir); continue; } file_information(filepath); //printf("%s\n", dir_struct->d_name); print_filename(dir_struct->d_name, filepath); dir_struct = readdir(dir); } closedir(dir); } } //-al命令,显示目录所有文件信息 void bianli_dir_al(char *dirname){ DIR *dir = opendir(dirname); struct dirent *dir_struct = readdir(dir); char filepath[4096]; while(dir_struct){ sprintf(filepath, "%s/%s", dirname, dir_struct->d_name); file_information(filepath); //printf("%s\n", dir_struct->d_name); print_filename(dir_struct->d_name, filepath); dir_struct = readdir(dir); //if(dir_struct == NULL){ // printf("line:%d\n", __LINE__-2); // perror("readdir"); // } // } closedir(dir); } //-aR选项 void bianli_dir_aR(char *dirname){ char filepath[4096]; DIR *dir = opendir(dirname); struct dirent *dir_struct = readdir(dir); while(dir_struct){ //printf("a\n"); sprintf(filepath, "%s/%s", dirname, dir_struct->d_name); //printf("%s\n", filepath); if(dir_struct->d_type == DT_REG){ dir_struct = readdir(dir); continue; } else if(dir_struct->d_type == DT_DIR){ if(strcmp(dir_struct->d_name, "..") == 0){ dir_struct = readdir(dir); continue; } else if(strcmp(dir_struct->d_name, ".") == 0){ printf(".:\n"); bianli_dir_easy_a(filepath); } else{ printf("%s:\n", filepath); bianli_dir_easy_a(filepath); } } dir_struct = readdir(dir); } closedir(dir); }
the_stack_data/98575572.c
double function() { int a = 1, b = 0; return a <= b; }
the_stack_data/36074305.c
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Mupen64plus - savestate_convert.c * * Mupen64Plus homepage: http://code.google.com/p/mupen64plus/ * * Copyright (C) 2008 Richard Goedeken * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include <zlib.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /* savestate file header: magic number and version number */ const char *savestate_magic = "M64+SAVE"; const int savestate_newest_version = 0x00010000; // 1.0 /* Data field lengths */ #define SIZE_REG_RDRAM 40 #define SIZE_REG_MIPS 36 #define SIZE_REG_PI 52 #define SIZE_REG_SP 52 #define SIZE_REG_RSP 8 #define SIZE_REG_SI 16 #define SIZE_REG_VI 60 #define SIZE_REG_RI 32 #define SIZE_REG_AI 40 #define SIZE_REG_DPC 48 #define SIZE_REG_DPS 16 #define SIZE_FLASHRAM_INFO 24 #define SIZE_TLB_ENTRY 52 #define SIZE_MAX_EVENTQUEUE 1024 /* Arrays and pointers for savestate data */ char rom_md5[32]; char rdram_register[SIZE_REG_RDRAM]; char mips_register[SIZE_REG_MIPS]; char pi_register[SIZE_REG_PI]; char sp_register[SIZE_REG_SP]; char rsp_register[SIZE_REG_RSP]; char si_register[SIZE_REG_SI]; char vi_register[SIZE_REG_VI]; char ri_register[SIZE_REG_RI]; char ai_register[SIZE_REG_AI]; char dpc_register[SIZE_REG_DPC]; char dps_register[SIZE_REG_DPS]; char *rdram; /* 0x800000 bytes */ char SP_DMEM[0x1000]; char SP_IMEM[0x1000]; char PIF_RAM[0x40]; char flashram[SIZE_FLASHRAM_INFO]; char *tlb_LUT_r; /* 0x400000 bytes */ char *tlb_LUT_w; /* 0x400000 bytes */ char llbit[4]; char reg[32][8]; char g_cp0_regs[32][4]; char lo[8]; char hi[8]; char reg_cop1_fgr_64[32][8]; char FCR0[4]; char FCR31[4]; char tlb_e[32][SIZE_TLB_ENTRY]; char PCaddr[4]; char next_interrupt[4]; char next_vi[4]; char vi_field[4]; char eventqueue[SIZE_MAX_EVENTQUEUE]; /* savestate data parameters calculated from file contents */ int queuelength = 0; /* Forward declarations for functions */ void printhelp(const char *progname); int allocate_memory(void); void free_memory(void); int load_original_mupen64(const char *filename); int save_newest(const char *filename); /* Main Function - parse arguments, check version, load state file, overwrite state file with new one */ int main(int argc, char *argv[]) { FILE *pfTest; gzFile f; char *filename; char magictag[8]; unsigned char inbuf[4]; int (*load_function)(const char *) = NULL; int iVersion; /* start by parsing the command-line arguments */ if (argc != 2 || strncmp(argv[1], "-h", 2) == 0 || strncmp(argv[1], "--help", 6) == 0) { printhelp(argv[0]); return 1; } filename = argv[1]; pfTest = fopen(filename, "rb"); if (pfTest == NULL) { printf("Error: cannot open savestate file '%s' for reading.\n", filename); return 2; } fclose(pfTest); /* try to determine the version of this savestate file */ f = gzopen(filename, "rb"); if (f == NULL) { printf("Error: state file '%s' is corrupt\n", filename); return 3; } if (gzread(f, magictag, 8) != 8 || gzread(f, inbuf, 4) != 4) { printf("Error: state file '%s' is corrupt: end of savestate file while reading header.\n", filename); gzclose(f); return 4; } gzclose(f); iVersion = inbuf[0]; iVersion = (iVersion << 8) | inbuf[1]; iVersion = (iVersion << 8) | inbuf[2]; iVersion = (iVersion << 8) | inbuf[3]; /* determine which type of savestate file to load, based on savestate version */ if (strncmp(magictag, savestate_magic, 8) != 0) { printf("Warning: old savestate file format. This is presumed to be from the original Mupen64 or Mupen64Plus version 1.4 or earlier.\n"); load_function = load_original_mupen64; } else if (iVersion == savestate_newest_version) { printf("This savestate file is already up to date (version %08x)\n", savestate_newest_version); return 0; } else { printf("This savestate file uses an unknown version (%08x)\n", iVersion); return 5; } /* allocate memory for savestate data */ if (allocate_memory() != 0) { printf("Error: couldn't allocate memory for savestate data storage.\n"); return 6; } /* load the savestate file */ if (load_function(filename) != 0) { free_memory(); return 7; } /* write new updated savestate file */ if (save_newest(filename) != 0) { free_memory(); return 8; } /* free the memory and return */ printf("Savestate file '%s' successfully converted to latest version (%08x).\n", filename, savestate_newest_version); free_memory(); return 0; } void printhelp(const char *progname) { printf("%s - convert older Mupen64Plus savestate files to most recent version.\n\n", progname); printf("Usage: %s [-h] [--help] <savestatepath>\n\n", progname); printf(" -h, --help: display this message\n"); printf(" <savestatepath>: full path to savestate file which will be overwritten with latest version.\n"); } int allocate_memory(void) { rdram = malloc(0x800000); if (rdram == NULL) return 1; tlb_LUT_r = malloc(0x400000); if (tlb_LUT_r == NULL) { free_memory(); return 2; } tlb_LUT_w = malloc(0x400000); if (tlb_LUT_w == NULL) { free_memory(); return 3; } return 0; } void free_memory(void) { if (rdram != NULL) { free(rdram); rdram = NULL; } if (tlb_LUT_r != NULL) { free(tlb_LUT_r); tlb_LUT_r = NULL; } if (tlb_LUT_w != NULL) { free(tlb_LUT_w); tlb_LUT_w = NULL; } } /* State Loading Functions */ int load_original_mupen64(const char *filename) { char buffer[4]; int i; gzFile f; f = gzopen(filename, "rb"); if (f == NULL) { printf("Error: savestate file '%s' is corrupt.\n", filename); return 1; } gzread(f, rom_md5, 32); gzread(f, rdram_register, SIZE_REG_RDRAM); gzread(f, mips_register, SIZE_REG_MIPS); gzread(f, pi_register, SIZE_REG_PI); gzread(f, sp_register, SIZE_REG_SP); gzread(f, rsp_register, SIZE_REG_RSP); gzread(f, si_register, SIZE_REG_SI); gzread(f, vi_register, SIZE_REG_VI); gzread(f, ri_register, SIZE_REG_RI); gzread(f, ai_register, SIZE_REG_AI); gzread(f, dpc_register, SIZE_REG_DPC); gzread(f, dps_register, SIZE_REG_DPS); gzread(f, rdram, 0x800000); gzread(f, SP_DMEM, 0x1000); gzread(f, SP_IMEM, 0x1000); gzread(f, PIF_RAM, 0x40); gzread(f, flashram, SIZE_FLASHRAM_INFO); memset(tlb_LUT_r, 0, 0x400000); memset(tlb_LUT_w, 0, 0x400000); gzread(f, tlb_LUT_r, 0x100000); gzread(f, tlb_LUT_w, 0x100000); gzread(f, llbit, 4); gzread(f, reg, 32*8); for (i = 0; i < 32; i++) { gzread(f, g_cp0_regs[i], 4); gzread(f, buffer, 4); /* for compatibility with older versions. */ } gzread(f, lo, 8); gzread(f, hi, 8); gzread(f, reg_cop1_fgr_64[0], 32 * 8); gzread(f, FCR0, 4); gzread(f, FCR31, 4); gzread(f, tlb_e[0], 32 * SIZE_TLB_ENTRY); gzread(f, PCaddr, 4); gzread(f, next_interrupt, 4); gzread(f, next_vi, 4); gzread(f, vi_field, 4); queuelength = 0; while(queuelength < SIZE_MAX_EVENTQUEUE) { if (gzread(f, eventqueue + queuelength, 4) != 4) { printf("Error: savestate file '%s' is corrupt.\n", filename); return 2; } if (*((unsigned int*) &eventqueue[queuelength]) == 0xFFFFFFFF) { queuelength += 4; break; } gzread(f, eventqueue + queuelength + 4, 4); queuelength += 8; } if (queuelength >= SIZE_MAX_EVENTQUEUE) { printf("Error: savestate file '%s' has event queue larger than %i bytes.\n", filename, SIZE_MAX_EVENTQUEUE); return 3; } gzclose(f); return 0; } /* State Saving Functions */ int save_newest(const char *filename) { unsigned char outbuf[4]; gzFile f; f = gzopen(filename, "wb"); /* write magic number */ gzwrite(f, savestate_magic, 8); /* write savestate file version in big-endian */ outbuf[0] = (savestate_newest_version >> 24) & 0xff; outbuf[1] = (savestate_newest_version >> 16) & 0xff; outbuf[2] = (savestate_newest_version >> 8) & 0xff; outbuf[3] = (savestate_newest_version >> 0) & 0xff; gzwrite(f, outbuf, 4); gzwrite(f, rom_md5, 32); gzwrite(f, rdram_register, SIZE_REG_RDRAM); gzwrite(f, mips_register, SIZE_REG_MIPS); gzwrite(f, pi_register, SIZE_REG_PI); gzwrite(f, sp_register, SIZE_REG_SP); gzwrite(f, rsp_register, SIZE_REG_RSP); gzwrite(f, si_register, SIZE_REG_SI); gzwrite(f, vi_register, SIZE_REG_VI); gzwrite(f, ri_register, SIZE_REG_RI); gzwrite(f, ai_register, SIZE_REG_AI); gzwrite(f, dpc_register, SIZE_REG_DPC); gzwrite(f, dps_register, SIZE_REG_DPS); gzwrite(f, rdram, 0x800000); gzwrite(f, SP_DMEM, 0x1000); gzwrite(f, SP_IMEM, 0x1000); gzwrite(f, PIF_RAM, 0x40); gzwrite(f, flashram, SIZE_FLASHRAM_INFO); gzwrite(f, tlb_LUT_r, 0x400000); gzwrite(f, tlb_LUT_w, 0x400000); gzwrite(f, llbit, 4); gzwrite(f, reg[0], 32*8); gzwrite(f, g_cp0_regs[0], 32*4); gzwrite(f, lo, 8); gzwrite(f, hi, 8); gzwrite(f, reg_cop1_fgr_64[0], 32*8); gzwrite(f, FCR0, 4); gzwrite(f, FCR31, 4); gzwrite(f, tlb_e[0], 32 * SIZE_TLB_ENTRY); gzwrite(f, PCaddr, 4); gzwrite(f, next_interrupt, 4); gzwrite(f, next_vi, 4); gzwrite(f, vi_field, 4); gzwrite(f, eventqueue, queuelength); gzclose(f); return 0; }
the_stack_data/137308.c
#include <stdio.h> #include <stdlib.h> int main(){ system("man ls | grep ls | wc -l"); }
the_stack_data/71835.c
/*Exercise 4 - Functions Implement the three functions minimum(), maximum() and multiply() below the main() function. Do not change the code given in the main() function when you are implementing your solution.*/ #include <stdio.h> int minimum(int no1, int no2); int maximum(int no1, int no2); int multiply(int no1, int no2); int main() { int no1, no2; printf("Enter a value for no 1 : "); scanf("%d", &no1); printf("Enter a value for no 2 : "); scanf("%d", &no2); printf("%d ", minimum(no1, no2)); printf("%d ", maximum(no1, no2)); printf("%d ", multiply(no1, no2)); return 0; } int minimum(int no1, int no2) { return (no1 > no2) ? no2 : no1; } int maximum(int no1, int no2) { return (no1 > no2) ? no1 : no2; } int multiply(int no1, int no2) { int output; output = no1 * no2; return output; }
the_stack_data/478651.c
static void f(void) { int *p, x; x = (sizeof (int))[p]; x = sizeof p[1]; }
the_stack_data/93020.c
#include <stdio.h> int merrno; /* modem error return code */ char *_merr_list[] = { "No error", "Interrupt occurred", /* M_INTRPT */ "Dialer Hung", /* M_D_HUNG */ "No answer", /* M_NO_ANS */ "Illegal baud rate", /* M_ILL_BD */ "ACU Problem", /* M_A_PROB */ "Line Problem", /* M_L_PROB */ "Can't open LDEVS file", /* M_NO_LDV */ "Requested device not available", /* M_DV_NT_A */ "Requested device not known", /* M_DV_NT_K */ "No device available at requested baud", /* M_NO_BD_A */ "No device known at requested baud", /* M_NO_BD_K */ "Incompatible telephone num and device chosen" /* M_DEV_TEL */ }; int _msys_nerr = (sizeof (_merr_list) / sizeof (char *)); merror (s) char *s; { int i = -merrno; if (0 <= i && i < _msys_nerr) fprintf (stderr, "%s: %s\n", s, _merr_list[i]); else fprintf (stderr, "%s: Error %d\n", s, merrno); }
the_stack_data/12636510.c
#include <math.h> #include <stdlib.h> double gasdev (void) { static int iset = 0; static double gset; double fac, rsq, v1, v2; if (iset == 0) { do { v1 = 2.0 * drand48 () - 1.0; v2 = 2.0 * drand48 () - 1.0; rsq = v1 * v1 + v2 * v2; } while (rsq >= 1.0 || rsq == 0.0); fac = sqrt (-2.0 * log (rsq) / rsq); gset = v1 * fac; iset = 1; return v2 * fac; } else { iset = 0; return gset; } }
the_stack_data/73566.c
/*** * 嵌入式linux操作framebuffer显示bmp图片 * https://blog.csdn.net/Bruno_Mars/article/details/94404842 * */ #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <string.h> #include <linux/fb.h> #include <sys/mman.h> #include <sys/ioctl.h> #include <arpa/inet.h> #include <errno.h> // 14byte BMP 文件头 typedef struct { char cfType[2]; //文件类型,"BM"(0x4D42) int cfSize; //文件大小(字节) int cfReserved; //保留,值为0 int cfoffBits; //数据区相对于文件头的偏移量(字节) } __attribute__((packed)) BITMAPFILEHEADER; //__attribute__((packed))的作用是告诉编译器取消结构在编译过程中的优化对齐 // 40byte 信息头 typedef struct { char ciSize[4]; //BITMAPFILEHEADER所占的字节数 int ciWidth; //宽度 int ciHeight; //高度 char ciPlanes[2]; //目标设备的位平面数,值为1 int ciBitCount; //每个像素的位数 char ciCompress[4]; //压缩说明 char ciSizeImage[4]; //用字节表示的图像大小,该数据必须是4的倍数 char ciXPelsPerMeter[4]; //目标设备的水平像素数/米 char ciYPelsPerMeter[4]; //目标设备的垂直像素数/米 char ciClrUsed[4]; //位图使用调色板的颜色数 char ciClrImportant[4]; //指定重要的颜色数,当该域的值等于颜色数时(或者等于0时),表示所有颜色都一样重要 } __attribute__((packed)) BITMAPINFOHEADER; typedef struct { unsigned char blue; unsigned char green; unsigned char red; unsigned char reserved; } __attribute__((packed)) PIXEL; //颜色模式RGB typedef struct { int fbfd; char *fbp; unsigned int xres; unsigned int yres; unsigned int xres_virtual; unsigned int yres_virtual; unsigned int xoffset; unsigned int yoffset; unsigned int bpp; unsigned long line_length; unsigned long size; struct fb_bitfield red; struct fb_bitfield green; struct fb_bitfield blue; } FB_INFO; typedef struct { unsigned int width; unsigned int height; unsigned int bpp; unsigned long size; unsigned int data_offset; } IMG_INFO; FB_INFO fb_info; IMG_INFO img_info; int show_bmp(char *img_name); static int cursor_bitmap_format_convert(char *dst, char *src, unsigned long img_len_one_line) { int img_len, fb_len; char *p; __u32 val; PIXEL pix; p = (char *)&val; img_len = img_info.width; /*一行图片的长度*/ fb_len = fb_info.xres; /*一行显示屏的长度*/ /*进行x轴的偏移*/ dst += fb_info.xoffset * (fb_info.bpp / 8); fb_len -= fb_info.xoffset; /*bmp 数据是上下左右颠倒的,这里只进行左右的处理*/ /*先定位到图片的最后一个像素的地址,然后往第一个像素的方向处理,进行左右颠倒的处理*/ src += img_len_one_line - 1; /*处理一行要显示的数据*/ while (1) { if (img_info.bpp == 32) pix.reserved = *(src--); pix.red = *(src--); pix.green = *(src--); pix.blue = *(src--); val = 0x00; val |= (pix.red >> (8 - fb_info.red.length)) << fb_info.red.offset; val |= (pix.green >> (8 - fb_info.green.length)) << fb_info.green.offset; val |= (pix.blue >> (8 - fb_info.blue.length)) << fb_info.blue.offset; if (fb_info.bpp == 16) { *(dst++) = *(p + 0); *(dst++) = *(p + 1); } else if (fb_info.bpp == 24) { *(dst++) = *(p + 0); *(dst++) = *(p + 1); *(dst++) = *(p + 2); } else if (fb_info.bpp == 32) { *(dst++) = *(p + 0); *(dst++) = *(p + 1); *(dst++) = *(p + 2); *(dst++) = *(p + 3); } /*超过图片长度或显示屏长度认为一行处理完了*/ img_len--; fb_len--; if (img_len <= 0 || fb_len <= 0) break; } #if 0 printf("r = %d\n", pix.red); printf("g = %d\n", pix.green); printf("b = %d\n", pix.blue); #endif return 0; } int show_bmp(char *img_name) { FILE *fp; int ret = 0; BITMAPFILEHEADER FileHead; BITMAPINFOHEADER InfoHead; if (img_name == NULL) { printf("img_name is null\n"); return -1; } fp = fopen(img_name, "rb"); if (fp == NULL) { printf("img[%s] open failed\n", img_name); ret = -1; goto err_showbmp; } /* 移位到文件头部 */ fseek(fp, 0, SEEK_SET); ret = fread(&FileHead, sizeof(BITMAPFILEHEADER), 1, fp); if (ret != 1) { printf("img read failed\n"); ret = -1; goto err_showbmp; } //检测是否是bmp图像 if (memcmp(FileHead.cfType, "BM", 2) != 0) { printf("it's not a BMP file[%c%c]\n", FileHead.cfType[0], FileHead.cfType[1]); ret = -1; goto err_showbmp; } ret = fread((char *)&InfoHead, sizeof(BITMAPINFOHEADER), 1, fp); if (ret != 1) { printf("read infoheader error!\n"); ret = -1; goto err_showbmp; } img_info.width = InfoHead.ciWidth; img_info.height = InfoHead.ciHeight; img_info.bpp = InfoHead.ciBitCount; img_info.size = FileHead.cfSize; img_info.data_offset = FileHead.cfoffBits; printf("img info w[%d] h[%d] bpp[%d] size[%ld] offset[%d]\n", img_info.width, img_info.height, img_info.bpp, img_info.size, img_info.data_offset); if (img_info.bpp != 24 && img_info.bpp != 32) { printf("img bpp is not 24 or 32\n"); ret = -1; goto err_showbmp; } /* *一行行处理 */ char *buf_img_one_line; char *buf_fb_one_line; char *p; int fb_height; long img_len_one_line = img_info.width * (img_info.bpp / 8); long fb_len_one_line = fb_info.line_length; printf("img_len_one_line = %d\n", img_len_one_line); printf("fb_len_one_line = %d\n", fb_info.line_length); buf_img_one_line = (char *)calloc(1, img_len_one_line + 256); if (buf_img_one_line == NULL) { printf("alloc failed\n"); ret = -1; goto err_showbmp; } buf_fb_one_line = (char *)calloc(1, fb_len_one_line + 256); if (buf_fb_one_line == NULL) { printf("alloc failed\n"); ret = -1; goto err_showbmp; } fseek(fp, img_info.data_offset, SEEK_SET); p = fb_info.fbp + fb_info.yoffset * fb_info.line_length; /*进行y轴的偏移*/ fb_height = fb_info.yres; while (1) { memset(buf_img_one_line, 0, img_len_one_line); memset(buf_fb_one_line, 0, fb_len_one_line); ret = fread(buf_img_one_line, 1, img_len_one_line, fp); if (ret < img_len_one_line) { /*图片读取完成,则图片显示完成*/ printf("read to end of img file\n"); cursor_bitmap_format_convert(buf_fb_one_line, buf_img_one_line, img_len_one_line); /*数据转换*/ memcpy(fb_info.fbp, buf_fb_one_line, fb_len_one_line); break; } cursor_bitmap_format_convert(buf_fb_one_line, buf_img_one_line, img_len_one_line); /*数据转换*/ memcpy(p, buf_fb_one_line, fb_len_one_line); /*显示一行*/ p += fb_len_one_line; /*超过显示屏宽度认为图片显示完成*/ fb_height--; if (fb_height <= 0) break; } free(buf_img_one_line); free(buf_fb_one_line); fclose(fp); return ret; err_showbmp: if (fp) fclose(fp); return ret; } int show_picture(char *img_name) { struct fb_var_screeninfo vinfo; struct fb_fix_screeninfo finfo; if (fb_info.fbfd <= -1) { printf("fb open fialed\n"); return -1; } if (ioctl(fb_info.fbfd, FBIOGET_FSCREENINFO, &finfo)) { printf("fb ioctl fialed\n"); return -1; } if (ioctl(fb_info.fbfd, FBIOGET_VSCREENINFO, &vinfo)) { printf("fb ioctl fialed\n"); return -1; } fb_info.xres = vinfo.xres; fb_info.yres = vinfo.yres; fb_info.xres_virtual = vinfo.xres_virtual; fb_info.yres_virtual = vinfo.yres_virtual; fb_info.xoffset = vinfo.xoffset; fb_info.yoffset = vinfo.yoffset; fb_info.bpp = vinfo.bits_per_pixel; fb_info.line_length = finfo.line_length; fb_info.size = finfo.smem_len; memcpy(&fb_info.red, &vinfo.red, sizeof(struct fb_bitfield)); memcpy(&fb_info.green, &vinfo.green, sizeof(struct fb_bitfield)); memcpy(&fb_info.blue, &vinfo.blue, sizeof(struct fb_bitfield)); printf("fb info x[%d] y[%d] x_v[%d] y_v[%d] xoffset[%d] yoffset[%d] bpp[%d] line_length[%ld] size[%ld]\n", fb_info.xres, fb_info.yres, fb_info.xres_virtual, fb_info.yres_virtual, fb_info.xoffset, fb_info.yoffset, fb_info.bpp, fb_info.line_length, fb_info.size); printf("fb info red off[%d] len[%d] msb[%d]\n", fb_info.red.offset, fb_info.red.length, fb_info.red.msb_right); printf("fb info green off[%d] len[%d] msb[%d]\n", fb_info.green.offset, fb_info.green.length, fb_info.green.msb_right); printf("fb info blue off[%d] len[%d] msb[%d]\n", fb_info.blue.offset, fb_info.blue.length, fb_info.blue.msb_right); if (fb_info.bpp != 16 && fb_info.bpp != 24 && fb_info.bpp != 32) { printf("fb bpp is not 16,24 or 32\n"); return -1; } if (fb_info.red.length > 8 || fb_info.green.length > 8 || fb_info.blue.length > 8) { printf("fb red|green|blue length is invalid\n"); return -1; } // 内存映射 fb_info.fbp = (char *)mmap(0, fb_info.size, PROT_READ | PROT_WRITE, MAP_SHARED, fb_info.fbfd, 0); if (fb_info.fbp == (char *)-1) { printf("mmap fialed\n"); return -1; } show_bmp(img_name); //删除映射 munmap(fb_info.fbp, fb_info.size); return 0; } int main(int argc, char **argv) { printf("====================\r\n"); printf("%s:%s\r\n", __DATE__, __TIME__); printf("====================\r\n"); char img_name[64]; if (argc != 2) { printf("arg error\n"); return 0; } snprintf(img_name, sizeof(img_name), "%s", argv[1]); printf("img_name = %s\n", img_name); fb_info.fbfd = open("/dev/fb0", O_RDWR); if (!fb_info.fbfd) { printf("Error: cannot open framebuffer device(/dev/fb0).\n"); return -1; } show_picture(img_name); close(fb_info.fbfd); return 0; }
the_stack_data/218892772.c
#include<stdio.h> #include<assert.h> int main() { int rd, rs, rt; int result; rs = 0x11777066; rt = 0x55AA33FF; result = 0x02; __asm ("cmp.le.ph %1, %2\n\t" "rddsp %0\n\t" : "=r"(rd) : "r"(rs), "r"(rt) ); rd = (rd >> 24) & 0x03; assert(rd == result); rs = 0x11777066; rt = 0x11777066; result = 0x03; __asm ("cmp.le.ph %1, %2\n\t" "rddsp %0\n\t" : "=r"(rd) : "r"(rs), "r"(rt) ); rd = (rd >> 24) & 0x03; assert(rd == result); return 0; }
the_stack_data/12637698.c
/* catanf.c */ /* Contributed by Danny Smith 2004-12-24 FIXME: This needs some serious numerical analysis. */ #include <math.h> #include <complex.h> #ifndef UNDER_CE #include <errno.h> #endif /* catan (z) = -I/2 * clog ((I + z) / (I - z)) */ float complex catanf (float complex Z) { float complex Res; float complex Tmp; float x = __real__ Z; float y = __imag__ Z; if ( x == 0.0f && (1.0f - fabsf (y)) == 0.0f) { #ifndef UNDER_CE errno = ERANGE; #endif __real__ Res = HUGE_VALF; __imag__ Res = HUGE_VALF; } else if (isinf (hypotf (x, y))) { __real__ Res = (x > 0 ? M_PI_2 : -M_PI_2); __imag__ Res = 0.0f; } else { __real__ Tmp = - x; __imag__ Tmp = 1.0f - y; __real__ Res = x; __imag__ Res = y + 1.0f; Tmp = clogf (Res/Tmp); __real__ Res = - 0.5f * __imag__ Tmp; __imag__ Res = 0.5f * __real__ Tmp; } return Res; }
the_stack_data/940738.c
/*Exercise 4 - Functions Implement the three functions minimum(), maximum() and multiply() below the main() function. Do not change the code given in the main() function when you are implementing your solution.*/ #include <stdio.h> int minimum(int no1, int no2); int maximum(int no1, int no2); int multiply(int no1, int no2); int main() { int no1, no2; printf("Enter a value for no 1 : "); scanf("%d", &no1); printf("Enter a value for no 2 : "); scanf("%d", &no2); printf("%d ", minimum(no1, no2)); printf("%d ", maximum(no1, no2)); printf("%d ", multiply(no1, no2)); return 0; } minimum(int no1, int no2) { if(no1>no2) { return no2; } else { return no1; } } maximum(int no1, int no2) { if(no1>no2) { return no1; } else { return no2; } } multiply(int no1, int no2) { return no1*no2; }
the_stack_data/54220.c
#include <stdio.h> int main() { printf("Hello, World!!!!!!\n"); }
the_stack_data/28261816.c
/* Assign n blocks of memory of size_t size Memory blocks are initialised to 0 */ #include <stdio.h> #include <stdlib.h> int main() { int numberOfNumbers, sum = 0; printf("Please enter number of numbers: "); scanf("%d", &numberOfNumbers); int *numbers = (int *)calloc(numberOfNumbers, sizeof(int)); if(numbers == NULL) { printf("Memory allocation unsuccefull"); exit(1); } for(int i = 0; i < numberOfNumbers; i++) { printf("Please provide a number: "); scanf("%d", numbers + i); } for(int i = 0; i < numberOfNumbers; i++) { sum += *(numbers + i); } printf("Total sum of the numbers is: %d\n", sum); return 0; }
the_stack_data/104828465.c
//@ #include "nat.gh" /*@ lemma void induction(nat n1, nat n2) requires true; ensures true; { switch(n1) { case succ(n10): switch(n2) { case succ(n20): induction(zero, n10); //~ case zero: } case zero: } } @*/
the_stack_data/142555.c
/* * switch_example.c (c) 2018-20 Christopher A. Bohn */ #include <stdio.h> #include <stdlib.h> void using_switch(int value) { switch (value) { case 1: printf("One\n"); break; case 2: printf("Two\n"); // fall through case 3: printf("Or maybe three\n"); break; case 4: case 5: printf("Four "); printf("or five\n"); break; default: printf("Greater than five or less than one\n"); } } void using_if(int value) { if (value == 1) { printf("One\n"); } if (value == 2) { printf("Two\n"); } if (value == 2 || value == 3) { printf("Or maybe three\n"); } if (value == 4 || value == 5) { printf("Four "); printf("or five\n"); } if (value < 1 || value > 5) { printf("Greater than five or less than one\n"); } } int main(int argc, const char **argv) { int value = (int)strtol(argv[1], NULL, 0); printf("%d is ", value); using_if(value); printf("\n"); printf("%d is ", value); using_switch(value); printf("\n"); }
the_stack_data/15762786.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() { float mark1,mark2,Avg; printf ("Enter mark 1 : "); scanf ("%f",&mark1); printf ("Enter mark 2 : "); scanf ("%f",&mark2); Avg = (mark1+mark2)/2; printf ("Average mark is : %.1f",Avg); return 0; }
the_stack_data/225143263.c
void fence() { asm("sync"); } void lwfence() { asm("lwsync"); } void isync() { asm("isync"); } int __unbuffered_cnt=0; int __unbuffered_p0_EAX=0; int x=0; int y=0; int z=0; void * P0(void * arg) { z = 2; fence(); __unbuffered_p0_EAX = x; // Instrumentation for CPROVER fence(); __unbuffered_cnt++; } void * P1(void * arg) { x = 1; y = 1; // Instrumentation for CPROVER fence(); __unbuffered_cnt++; } void * P2(void * arg) { y = 2; z = 1; // Instrumentation for CPROVER fence(); __unbuffered_cnt++; } int main() { __CPROVER_ASYNC_0: P0(0); __CPROVER_ASYNC_1: P1(0); __CPROVER_ASYNC_2: P2(0); __CPROVER_assume(__unbuffered_cnt==3); fence(); // EXPECT:exists __CPROVER_assert(!(y==2 && z==2 && __unbuffered_p0_EAX==0), "Program was expected to be safe for X86, model checker should have said NO.\nThis likely is a bug in the tool chain."); return 0; }
the_stack_data/504079.c
/*** *is-little-endian.c * * 0x123456 --> is big endian * 0x563412 --> is little endian. */ #include <stdio.h> #include <assert.h> typedef unsigned char* byte_pointer; int is_little_endian() { int test_num = (~0x0) & (0xff); byte_pointer byte_start = (byte_pointer) &test_num; if ( byte_start[0] == 0xff) { return 1; } else { return 0; } } void main (void) { assert(is_little_endian()); }
the_stack_data/11074161.c
//Comentario Simple /* Author: Fernando Sánchez Mejia Fecha: 13-02-2020 Descripciopn: */ #include <stdio.h> //Libreria #include <math.h> int main (){ //funcion principal //Declaración de variables int iRadio; //Asignacion de valores float fLongitud, fArea, fRadioCuadrado ; //Declaración de valoriables const float PI = 3.1416; //Declaración de constante //Pedir datos a usuario printf("Dame el radio del c%crculo que deseas calcular: ", 161); scanf("%d", &iRadio); fRadioCuadrado = pow(iRadio,2); fLongitud = (2 * PI ) * iRadio; fArea = (PI * fRadioCuadrado); printf("\n El valor de radio es: %d y al cuadrado es igual a %0.0f", iRadio, fRadioCuadrado); printf("\n La longitud del c%crculo con radio %d es: %0.2f\n", 161, iRadio, fLongitud); printf("\n El %crea del c%crculo con radio %d es: %0.2f\n ", 160, 161, iRadio, fArea); /*-------------------------------------------------*/ printf("\n/------------------------------------------/\n"); int iRaiz; printf("\nDame un n%cmero para calcular raiz cuadrada: ", 163); scanf("%d", &iRaiz); printf("\n La raiz cuadrada del n%cmero %d es: %0.2f", 163, iRaiz, sqrt(iRaiz)); printf("\n/------------------------------------------/\n"); int iNum1, iNum2; printf("\nDame un n%cmero para sumar con otro numero: ", 163); scanf("%d", &iNum1); printf("\nDame un n%cmero para sumar con otro numero: ", 163); scanf("%d", &iNum2); printf("\n El resultado de la sumar: %d + %d = %d", iNum1,iNum2,iNum1+iNum2); printf("\n/------------------------------------------/\n"); int iNum3, iNum4; printf("\nDame un n%cmero para restar con otro numero: ", 163); scanf("%d", &iNum3); printf("\nDame un n%cmero para restar con otro numero: ", 163); scanf("%d", &iNum4); printf("\n El resultado de la restar: %d - %d = %d", iNum3,iNum4,iNum3-iNum4); return 0; }//fin int main
the_stack_data/151706969.c
/* -*- mode: C -*- */ /* IGraph library. Copyright (C) 2011-12 Gabor Csardi <[email protected]> 334 Harvard street, Cambridge MA, 02139 USA This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <float.h> double digitsdbl_(double *x) { return (double) DBL_MANT_DIG; } double epsilondbl_(double *x) { return DBL_EPSILON; } double hugedbl_(double *x) { return DBL_MAX; } double tinydbl_(double *x) { return DBL_MIN; } int maxexponentdbl_(double *x) { return DBL_MAX_EXP; } int minexponentdbl_(double *x) { return DBL_MIN_EXP; } double radixdbl_(double *x) { return (double) FLT_RADIX; }
the_stack_data/50138704.c
#include<stdio.h> int main() { printf("please enter the size of array to be used: \n"); int n,i; scanf("%d",&n); int a[n]; for(i=0;i<=n-1;i++) {printf("enter the no.:\n"); scanf("%d",&a[i]); } int key; printf("enter the no. to be searched in the array.\n"); scanf("%d",&key); int hi=n,mid,lo=0; while( lo <= hi ) { mid=(lo+hi)/2; if( a[mid] < key ) { lo = mid; } else if( a[mid] > key ) { hi = mid; } else if( a[mid] == key ) { printf(" the specified no. is at %dth position \n",mid ); break;} else{ printf("specified key is not present in the array."); } } return 0; }
the_stack_data/856601.c
#include <stdio.h> #include <sys/ioctl.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <termios.h> //String which a rocket using ASCII characters char rocket[12][20] ={ " _\n\ ", " /^\\\n\ ", " |-|\n\ ", " |R|\n\ ", " |O|\n\ ", " |C|\n\ ", " |K|\n\ ", " |E|\n\ ", " /|T|\\\n\ ", " / | | \\\n\ ", "| | | |\n\ ", " *-\"\"\"-*\n\ " }; int main() { system("clear"); struct winsize win; //struct winsize to get the window's width and height. ioctl(0, TIOCGWINSZ, &win); int columns = win.ws_col; int stringLength[12],i,j=300000; for(i = 0; i < 12; i ++) { stringLength[i]=strlen(rocket[i]); } for (i = 0; i < win.ws_col; i ++) printf("\n"); for (i = 0; i < 12; i ++) { printf("%*s", columns/2 + stringLength[i] - 4, rocket[i]); } for ( i = 0; i < win.ws_row; i++) { usleep(j); j = (int)(j * 0.92); printf("\n"); } system("clear"); return 0; }
the_stack_data/151704571.c
// // main.c // Stack Using Array // // Created by Bikramjit Saha on 05/06/20. // Copyright © 2020 Bikramjit Saha. All rights reserved. // #include <stdio.h> #include <stdlib.h> struct Stack{ int size; int top; int *s; }; void create(struct Stack *stk){ printf("Enter the size:\n"); scanf("%d",&stk->size); stk->top=-1; stk->s=(int*)malloc(stk->size*sizeof(int)); } void Display(struct Stack stk){ int i; for (i=stk.top; i>=0; i--) { printf("%d ",stk.s[i]); } printf("\n"); } void Push(struct Stack *stk,int val){ // before inserting check stack is full or not if (stk->top==stk->size-1) { printf("Stack Overflow\n"); }else{ stk->top++; stk->s[stk->top]=val; } } int Pop(struct Stack *stk){ int Store=-1; if (stk->top==-1) { printf("Stack is Empty\n"); }else{ Store=stk->s[stk->top--]; } return Store; } int Peek(struct Stack stk,int pos){ int x=-1; if (stk.top-pos+1<0) { printf("Position is Invalid\n"); }else{ x=stk.s[stk.top-pos+1]; } return x; } int isEmpty(struct Stack stk){ if (stk.top==-1) { return 1; }else{ return 0; } } int StackTop(struct Stack stk){ if (!isEmpty(stk)) { return stk.s[stk.top]; }else{ return -1; } } int isFull(struct Stack stk){ if (stk.top==stk.size-1) { return 1; }else{ return 0; } } int main(int argc, const char * argv[]) { // insert code here... struct Stack stk; create(&stk); Push(&stk,20); Push(&stk,30); Push(&stk,40); Push(&stk,50); Push(&stk,60); Push(&stk,100); Display(stk); if (isEmpty(stk)) { printf("Yes,Stack is Empty\n"); }else{ printf("No,Stack is Not Empty\n"); } if (StackTop(stk)) { printf("%d\n",stk.s[stk.top]); } if (isFull(stk)) { printf("Stack is Full\n"); }else{ printf("Stack is Not Full\n"); } Pop(&stk); Display(stk); return 0; }
the_stack_data/7951243.c
#include <unistd.h> void mx_printchar(char c); int mx_strlen(const char *s); void mx_printstr(const char *s); int mx_strcmp(const char *s1, const char *s2); int main(int argc, char const *argv[]) { const char *temp; if (argc < 2) return 0; for (int i = 1; i < argc; ++i) { for (int j = i; j < argc; ++j) { if (mx_strcmp(argv[i], argv[j]) > 0) { temp = argv[j]; argv[j] = argv[i]; argv[i] = temp; } } } for (int i = 1; i < argc; ++i) { mx_printstr(argv[i]); mx_printchar('\n'); } return 0; }
the_stack_data/15761816.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>//function main begin program execution int main() { //variables int x,y; float average; printf("Enter the marks of first subject :"); scanf("%d",&x); printf("Enter the marks of second subject :"); scanf("%d",&y); average=(x+y)/2.0;//caculating average printf("average is %.2f",average);//print return 0;//end of the function main }
the_stack_data/190767753.c
#include <stdio.h> #include <stdlib.h> #define MAX 0x100 char input[MAX]; void BUG() { puts("Reach bug1"); strtok("QAQ", "A"); // booom } void BUG2() { puts("Reach bug2"); input[MAX + 1] = 0; } void BUG3() { puts("Reach bug3"); int n = read(0, input, 10); input[n - 1] = '\0'; printf(input); } int main() { puts("Mediatek Fuzzing Workshop in HITCON 2021!"); if (read(0, input, MAX) < 7) return -1; // if (!strcmp(input, "MTK")) // BUG(); if (input[0] == 'M') { if (input[1] == 'T') { if (input[2] == 'K') { if (*(int*)(&input[3]) == 0xdeadbeef) { BUG(); } } } } // BUG2(); // BUG3(); return 0; }
the_stack_data/129087.c
/* * * Test functions * * */ #include <stdio.h> #include <stdlib.h> unsigned int test(unsigned int (*tests[]) (void)) { for (int i = 0; tests[i] != NULL; i++) { if (tests[i]()) { printf("Error in test number %i.\n", i); return 1; } } return 0; }
the_stack_data/21536.c
/****************************************************************************** * File Name : poly_compute_flt.c * Date First Issued : 08/02/2015 * Board : * Description : Compute polynomial routine to compensate something *******************************************************************************/ /* ************************************************************************************** * double compensation_dbl(const float c[], int n, double t); * @brief : Compute polynomial of t * @param ; c = pointer to coefficients * @param : n = Number of coefficients (size of 'c' array) * @param : t = variable to be adjusted * @return : c[0] + c[1]*t + c[2]*t^2 + c[3]*t^3...+c[n-1]t^(n-1) * ************************************************************************************** */ double compensation_dbl(const float c[], int n, double t) { double x = c[0]; double tt = t; int i; for (i = 1; i < n; i++) { x += (c[i] * tt); tt *= t; } return x; }
the_stack_data/148577450.c
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/time.h> #include <math.h> typedef struct mat_elem { int re, rs, ce, cs; float **arr; }Matrix; Matrix * createMatrix(int n) { Matrix *m1 = (Matrix *)malloc(sizeof(Matrix)); int count = 0, i, j; m1->rs = 0; m1->cs = 0; m1->re = n - 1; m1->ce = n - 1; m1->arr = (float **)malloc(sizeof(float*) * n); m1->arr[0] = (float *)malloc(sizeof(float) * n * n); for (i = 0; i < n; i++) { m1->arr[i] = (*(m1->arr) + n * i); } for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { m1->arr[i][j] = ((double)rand() / (RAND_MAX)); // OR *(*(arr+i)+j) = ++count /*m1->arr[i][j] = 0.00;*/ } } return m1; } void displayMatrix(Matrix *m, int n) { int i, j; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { printf("%f ", m->arr[i][j]); } printf("\n"); } } Matrix* Normal_Multiply(Matrix *first, Matrix *second, int n) { float row_sum = 0; int i, j, k; Matrix *result = createMatrix(n); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { for (k = 0; k < n; k++) { row_sum += first->arr[i][k] * second->arr[k][j]; } result->arr[i][j] = row_sum; row_sum = 0; } } return result; } Matrix* mat_op(Matrix *m1, Matrix *m2, int n, int isAdd) {//no need to create a new matrix again, just use & to operate on the same matrix which was input as a formal parameter Matrix *m_result = createMatrix(n); int i, j; if (isAdd == 0) { for (i = 0; i<n; i++) { for (j = 0; j<n; j++) { m_result->arr[i][j] = m1->arr[i][j] + m2->arr[i][j]; } } } else { for (i = 0; i<n; i++) { for (j = 0; j<n; j++) { m_result->arr[i][j] = m1->arr[i][j] - m2->arr[i][j]; } } } return m_result; } Matrix* mat_add(Matrix *m1, Matrix *m2, int n) { return mat_op(m1, m2, n, 0); } Matrix* mat_sub(Matrix *m1, Matrix *m2, int n) { return mat_op(m1, m2, n, 1); } void copyArr(Matrix *dest, Matrix *source, /*int n, */int rs, int re, int cs, int ce) { int i, j; int i_dest, j_dest; float value; /*dest->rs = dest->cs = 0; dest->re = dest->ce = n / 2;*/ for (i = rs, i_dest = 0; i <= re; i++, i_dest++) { for (j = cs, j_dest = 0; j <= ce; j++, j_dest++) { value = source->arr[i][j]; dest->arr[i_dest][j_dest] = value; } } } Matrix* Strassen_Multiply(Matrix *m1, Matrix *m2, int n) { Matrix *A11, *A12, *A21, *A22, *B11, *B12, *B21, *B22; /* Matrices for storing the given matrices split */ Matrix *S1, *S2, *S3, *S4, *S5, *S6, *S7, *S8, *S9, *S10; /* 10 Matrices having sum or diffrences of previous 8 matrices */ Matrix *P1, *P2, *P3, *P4, *P5, *P6, *P7; /* Seven products */ Matrix *C11, *C12, *C21, *C22; /* Sub matrices of resultant matrix C*/ Matrix *result = createMatrix(n); int rowCounter, colCounter, resRowCounter, resColCounter; /*Below variables are for base case where we have 2 x 2 matrices*/ float a11, a12, a21, a22, b11, b12, b21, b22; float s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; float p1, p2, p3, p4, p5, p6, p7; Matrix* BASE_C = createMatrix(2); /*printf("\nStrassen start\n");*/ /* start base case calculation: perform basic multiplication to return the result of 2x2 matrix*/ if (n <= 2) { /*printf("\nBase case start\n");*/ a11 = m1->arr[0][0]; a12 = m1->arr[0][1]; a21 = m1->arr[1][0]; a22 = m1->arr[1][1]; b11 = m2->arr[0][0]; b12 = m2->arr[0][1]; b21 = m2->arr[1][0]; b22 = m2->arr[1][1]; s1 = b12 - b22; s2 = a11 + a12; s3 = a21 + a22; s4 = b21 - b11; s5 = a11 + a22; s6 = b11 + b22; s7 = a12 - a22; s8 = b21 + b22; s9 = a11 - a21; s10 = b11 + b12; p1 = a11 * s1; p2 = s2 * b22; p3 = s3 * b11; p4 = a22 * s4; p5 = s5 * s6; p6 = s7 * s8; p7 = s9 * s10; BASE_C->arr[0][0] = p5 + p4 - p2 + p6; BASE_C->arr[0][1] = p1 + p2; BASE_C->arr[1][0] = p3 + p4; BASE_C->arr[1][1] = p5 + p1 - p3 - p7; /*printf("\nBase case end\n");*/ return BASE_C; } /* end base case calculation*/ A11 = createMatrix(n / 2); A12 = createMatrix(n / 2); A21 = createMatrix(n / 2); A22 = createMatrix(n / 2); B11 = createMatrix(n / 2); B12 = createMatrix(n / 2); B21 = createMatrix(n / 2); B22 = createMatrix(n / 2); copyArr(A11, m1, m1->rs, m1->re / 2, m1->cs, m1->ce / 2);/* copy arrays based on the next block not just the same thing like this*/ copyArr(A12, m1, m1->rs, m1->re / 2, m1->ce / 2 + 1, m1->ce); copyArr(A21, m1, m1->re / 2 + 1, m1->re, m1->cs, m1->ce / 2); copyArr(A22, m1, m1->re / 2 + 1, m1->re, m1->ce / 2 + 1, m1->ce); copyArr(B11, m2, m2->rs, m2->re / 2, m2->cs, m2->ce / 2); copyArr(B12, m2, m2->rs, m2->re / 2, m2->ce / 2 + 1, m2->ce); copyArr(B21, m2, m2->re / 2 + 1, m2->re, m2->cs, m2->ce / 2); copyArr(B22, m2, m2->re / 2 + 1, m2->re, m2->ce / 2 + 1, m2->ce); S1 = mat_sub(B12, B22, n / 2); S2 = mat_add(A11, A12, n / 2); S3 = mat_add(A21, A22, n / 2); S4 = mat_sub(B21, B11, n / 2); S5 = mat_add(A11, A22, n / 2); S6 = mat_add(B11, B22, n / 2); S7 = mat_sub(A12, A22, n / 2); S8 = mat_add(B21, B22, n / 2); S9 = mat_sub(A11, A21, n / 2); S10 = mat_add(B11, B12, n / 2); P1 = createMatrix(n / 2); P2 = createMatrix(n / 2); P3 = createMatrix(n / 2); P4 = createMatrix(n / 2); P5 = createMatrix(n / 2); P6 = createMatrix(n / 2); P7 = createMatrix(n / 2); P1 = Strassen_Multiply(A11, S1, n / 2); P2 = Strassen_Multiply(S2, B22, n / 2); P3 = Strassen_Multiply(S3, B11, n / 2); P4 = Strassen_Multiply(A22, S4, n / 2); P5 = Strassen_Multiply(S5, S6, n / 2); P6 = Strassen_Multiply(S7, S8, n / 2); P7 = Strassen_Multiply(S9, S10, n / 2); C11 = createMatrix(n / 2); C12 = createMatrix(n / 2); C21 = createMatrix(n / 2); C22 = createMatrix(n / 2); C11 = mat_add(mat_sub(mat_add(P5, P4, n / 2), P2, n / 2), P6, n / 2); C12 = mat_add(P1, P2, n / 2); C21 = mat_add(P3, P4, n / 2); C22 = mat_sub(mat_sub(mat_add(P1, P5, n / 2), P3, n / 2), P7, n / 2); for (rowCounter = C11->rs, resRowCounter = 0; rowCounter <= C11->re; rowCounter++, resRowCounter++) { for (colCounter = C11->cs, resColCounter = 0; colCounter <= C11->ce; colCounter++, resColCounter++) { result->arr[resRowCounter][resColCounter] = C11->arr[rowCounter][colCounter]; } } for (rowCounter = C12->rs, resRowCounter = 0; rowCounter <= C12->re; rowCounter++, resRowCounter++) { for (colCounter = C12->cs, resColCounter = n / 2; colCounter <= C12->ce; colCounter++, resColCounter++) { result->arr[resRowCounter][resColCounter] = C12->arr[rowCounter][colCounter]; } } for (rowCounter = C21->rs, resRowCounter = n / 2; rowCounter <= C21->re; rowCounter++, resRowCounter++) { for (colCounter = C21->cs, resColCounter = 0; colCounter <= C21->ce; colCounter++, resColCounter++) { result->arr[resRowCounter][resColCounter] = C21->arr[rowCounter][colCounter]; } } for (rowCounter = C22->rs, resRowCounter = n / 2; rowCounter <= C22->re; rowCounter++, resRowCounter++) { for (colCounter = C22->cs, resColCounter = n / 2; colCounter <= C22->ce; colCounter++, resColCounter++) { result->arr[resRowCounter][resColCounter] = C22->arr[rowCounter][colCounter]; } } /*printf("\nStrassen end\n");*/ return result; } struct timeval GetTimeStamp() { struct timeval tv; gettimeofday(&tv, NULL); return tv; } int main(void) { int n, i, j; Matrix *mat1, *mat2, *normal_product, *strassen_product; /*time_t tn_start, tn_end, ts_start, ts_end;*/ long int tn_diff, ts_diff; struct timespec tn_start, tn_end, ts_start, ts_end; /* struct timeval tss_start, tss_end, tnn_start, tnn_end;*/ for (i = 1; i <= 3; i++) { n = pow(2, i); mat1 = createMatrix(n); mat2 = createMatrix(n); /*tn_start = time(NULL);*/ /*tn_start = GetTimeStamp();*/ clock_gettime(CLOCK_MONOTONIC, &tn_start); normal_product = Normal_Multiply(mat1, mat2, n); clock_gettime(CLOCK_MONOTONIC, &tn_end); /*tn_end = GetTimeStamp(); displayMatrix(normal_product, n); tn_end = time(NULL); tn_diff = difftime(tn_end, tn_start);*/ tn_diff = ((tn_end.tv_nsec - tn_start.tv_nsec)) / CLOCKS_PER_SEC; printf("\nProduct by normal method for n = %d:\n", n); displayMatrix(normal_product, n); /*ts_start = time(NULL); ts_start = GetTimeStamp();*/ clock_gettime(CLOCK_MONOTONIC, &ts_start); strassen_product = Strassen_Multiply(mat1, mat2, n); /*ts_end = time(NULL); ts_end = GetTimeStamp();*/ clock_gettime(CLOCK_MONOTONIC, &ts_end); /*ts_diff = difftime(ts_end, ts_start);*/ ts_diff = ((ts_end.tv_nsec - ts_start.tv_nsec)) / CLOCKS_PER_SEC; printf("\nProduct by normal method for n = %d:\n", n); displayMatrix(strassen_product, n); free(strassen_product); free(normal_product); free(mat1); free(mat2); } return 0; }
the_stack_data/234519350.c
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <unistd.h> int main(int argc, char **argv){ if (argc < 2) { printf("ERROR: Introduce el comando.\n"); return -1; } //Ejecutamos el comando correspondiente a la entrada por argumentos execvp(argv[1], argv + 1); printf("El comando terminó de ejecutarse.\n"); return 0; }
the_stack_data/110505.c
#include <stdio.h> int main(int argc, char *argv[]) { printf("Hello world!"); return 0; }
the_stack_data/100139801.c
#include <stdlib.h> int test () { int biv,giv; for (biv = 0, giv = 0; giv != 8; biv++) giv = biv*8; return giv; } int main() { if (test () != 8) abort (); exit (0); }
the_stack_data/638548.c
#include <stdio.h> #include <string.h> int rec(int n){ if(n<1) return 1; printf("%d", n%10); rec(n/=10); }; int main(){ int n; scanf("%d", &n); rec(n); return 0; }
the_stack_data/137243.c
#include <stdio.h> int main() { printf("Hello World!\n"); return 0; }
the_stack_data/103264561.c
/* list.c */ #include<stdio.h> int main(void){ /* int lst[] = {1, 2, 3, 4, 5}; lst[0] = 0; */ char lst[] = {'I', 'N', 'I', 'A', 'D',}; lst[2] = 'i'; for(int i = 0; i < 5; i++){ for(int j = 0; j < 5; j++){ printf("%c%c ", lst[i], lst[j]); } } return 0; }
the_stack_data/248579643.c
#include<stdio.h> #include<string.h> #include<math.h> #include<stdlib.h> void main() { char opc[20],opcode[20],opcnum[20],op[20],lbl[20],symbol[20],addr[20],ex[20],len[20],c; int locctr,sa,flag,flag2,i=2; FILE *finter,*foptab,*fsymtab,*fobject,*flen; finter = fopen("output.txt","r"); foptab = fopen("op.txt","r"); fsymtab = fopen("symtab.txt","r"); fobject = fopen("object.txt","w"); flen = fopen("len.txt","r"); fscanf(finter,"%s %s %s",lbl,opc,op); if(strcmp(opc,"START")==0) { sa = atoi(op); fscanf(flen,"%s",len); fprintf(fobject,"H^%s^%d^%s\n",lbl,sa,len); fscanf(finter,"%s %s %s %s",addr,lbl,opc,op); } fprintf(fobject,"T^%d^%s^",sa,len); while(strcmp(opc,"END") != 0) { flag2 = 0; rewind(foptab); fscanf(foptab,"%s %s",opcode,opcnum); while(!feof(foptab)) { if(strcmp(opc,opcode)==0) { flag2 = 1; break; } fscanf(foptab,"%s %s",opcode,opcnum); } if (flag2==1) { flag = 0; rewind(fsymtab); fscanf(fsymtab,"%s %s",symbol,addr); while(!feof(fsymtab)) { if(strcmp(op,symbol)==0) { flag = 1; break; } fscanf(fsymtab,"%s %s",symbol,addr); } if (flag==1) fprintf(fobject,"%s%s^",opcnum,addr); else printf("Invalid symbol\n"); } else if(strcmp(opc,"WORD")==0) { fprintf(fobject,"^00000%s",op); } else if(strcmp(opc,"BYTE")==0) { c=op[2]; fprintf(fobject,"^000"); while(c!='\'') { fprintf(fobject,"%c",c); i+=1; c=op[i]; } } fscanf(finter,"%s %s %s %s",addr,lbl,opc,op); } fprintf(fobject,"\nE^00%d",sa); fclose(foptab); fclose(fsymtab); }
the_stack_data/98575439.c
/** In mathematics we learn about matrix, a matrix is a table of data, which can be accessed in row and column manner detail link - https://en.wikipedia.org/wiki/Matrix_(mathematics) In the code series we will learn how to construct pyramid which is actually matrix. Here, we will learn about different type of pyramid(matrix) And try to construct them with c programming */ /** ***** ***** ***** ***** ***** this is a matrix which has 5 row and 5 column every cell of this matrix contains * symbol as data construct it with c programming */ #include <stdio.h> int main(int argc, char const *argv[]) { for (int row = 1; row <= 5; row++) { for (int col = 1; col <= 5; col++) { printf("*"); } printf("\n"); } return 0; }
the_stack_data/376399.c
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <sys/types.h> #include <sys/wait.h> #include <netdb.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <signal.h> #include <arpa/inet.h> #define PORT "3490" #define BACKLOG 10 void sigchld_handler() { int saved_errno = errno; while (waitpid(-1, NULL, WNOHANG) > 0); errno = saved_errno; } void* get_in_addr(struct sockaddr* sa) { if (sa->sa_family == AF_INET) return &(((struct sockaddr_in*)sa)->sin_addr); return &(((struct sockaddr_in6*)sa)->sin6_addr); } void config_getaddrinfo(struct addrinfo hints, struct addrinfo** servinfo, int* rv) { memset(&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; if ((*rv = getaddrinfo(NULL, PORT, &hints, servinfo)) != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(*rv)); exit(1); } else printf("[OK] addrinfo success\n"); } void config_bind(struct addrinfo** p, struct addrinfo* servinfo, int* sockfd, int* yes) { for (*p = servinfo; *p != NULL; *p = (*p)->ai_next) { if ((*sockfd = socket((*p)->ai_family, (*p)->ai_socktype, (*p)->ai_protocol)) == -1) { perror("server: socket"); continue; } if (setsockopt(*sockfd, SOL_SOCKET, SO_REUSEADDR, yes, sizeof(int)) == -1) { perror("setsockopt"); exit(1); } if (bind(*sockfd, (*p)->ai_addr, (*p)->ai_addrlen) == -1) { close(*sockfd); perror("server: bind"); continue; } break; } } void check_server_bind(struct addrinfo* p) { if (p == NULL) { fprintf(stderr, "server: failed to bind\n"); exit(1); } else printf("[OK] binding success\n"); } void config_listen(int sockfd) { if (listen(sockfd, BACKLOG) == -1) { perror("listen"); exit(1); } else printf("[OK] listening success\n"); } void sigaction_handler(struct sigaction sa) { sa.sa_handler = sigchld_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; if (sigaction(SIGCHLD, &sa, NULL) == -1) { perror("sigaction"); exit(1); } printf("server: waiting for connections...\n"); } void accept_loop(socklen_t* sin_size, struct sockaddr_storage storage_addr, int* new_fd, int* sockfd, int* bytes_sent) { char s[INET6_ADDRSTRLEN]; while (1) { *sin_size = sizeof storage_addr; *new_fd = accept(*sockfd, (struct sockaddr*)&storage_addr, sin_size); if (*new_fd == -1) { perror("accept"); continue; } inet_ntop(storage_addr.ss_family, get_in_addr((struct sockaddr*)&storage_addr), s, sizeof s); printf("server: got connection from %s\n", s); if (!fork()) { close(*sockfd); char msg[] = "Hello World!"; if ((*bytes_sent += send(*new_fd, msg, sizeof msg, 0)) == -1) perror("send"); printf("sent: %d bytes\n", *bytes_sent); close(*new_fd); exit(0); } close(*new_fd); } } int main() { int sockfd, new_fd; struct addrinfo hints, * servinfo, * p = NULL; struct sockaddr_storage storage_addr; socklen_t sin_size; struct sigaction sa; int yes = 1; int rv; int bytes_sent = 0; config_getaddrinfo(hints, &servinfo, &rv); config_bind(&p, servinfo, &sockfd, &yes); freeaddrinfo(servinfo); check_server_bind(p); config_listen(sockfd); sigaction_handler(sa); accept_loop(&sin_size, storage_addr, &new_fd, &sockfd, &bytes_sent); }
the_stack_data/479492.c
int EXPRESSION_and(int, int); int nondet_int(); int main() { int in0=nondet_int(), in1=nondet_int(); __CPROVER_assert(EXPRESSION_and(in0, in1)==(in0 & in1), ""); }
the_stack_data/28262786.c
/* BSD 3-Clause License Copyright (c) 2020, Masscollabs Services, Masscollaboration Labs, amassivus, procyberian, hwpplayers All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> int main(){ int second = 60, minute = 60, hour = 60, day = 24, week = 7, total; minute = second; hour = minute * 60; day = hour * 24; week = day * 7; total = week; printf("total second is : %d\n", total); return 0; } /*Let's dive into that code*/
the_stack_data/14201452.c
/* 1. Poniższy – zawierający wiele błędów – program dla podanej z klawiatury liczby M ma obliczyć najmniejszą liczbę n, taką że 1 + 2 + 3 +...+ n >= M Popraw wszystkie błędy w tym programie tak, aby poprawiony program prawidłowo obliczał liczbę n. #include <stdio.h> int main() { int M; suma = 0; i = 1; print("Podaj liczbe M: "); scanf("%f\n", %M) while (suma < M) { suma=suma+i; i=i+1; } n=i+1; printf("Szukane n to: ", n); return 0; } Na konsoli, działanie programu, może wyglądać tak: Podaj liczbę M: 11 Szukane n to: 5 Szukane n to 5, ponieważ: 1 + 2 + 3 + 4 < 10 1 + 2 + 3 + 4 + 5 >= 10 */ #include <stdio.h> int main() { int suma,i,n,M; suma = 0; i = 1; printf("Podaj liczbe M: "); scanf("%d", &M); while (suma < M) { suma=suma+i; i=i+1; } n=i-1; printf("Szukane n to: %d\n", n); return 0; }
the_stack_data/176704715.c
/* ================================================================================ Name : 1052.c Author : Abrantes Araújo Silva Filho : [email protected] : https://www.abrantes.pro.br Description : URI Online Judge: Problems & Contests : https://www.urionlinejudge.com.br/ Category : Beginner (1) Problem : 1052: Month URL : https://www.urionlinejudge.com.br/judge/en/problems/view/1052 Summary : Read an integer number between 1 and 12, including. Corresponding : to this number, you must print the month of the year, in english, : with the first letter in uppercase. C Standard : C99 Version : Copyright : More Info : ================================================================================ */ /* Headers files includes: -------------------------- */ #include <stdio.h> /* Preprocessor macros/definitions: ----------------------------------- */ #define rSucesso 0 /* Global variables declarations: --------------------------------- */ /* Functions prototypes (declarations): --------------------------------------- */ /* Main function: ----------------- */ int main(void) { // Declara variáveis int mes = 0; // Pega variáveis scanf("%d", &mes); // Imprime if ( mes == 1 ) printf("January\n"); else if ( mes == 2 ) printf("February\n"); else if ( mes == 3 ) printf("March\n"); else if ( mes == 4 ) printf("April\n"); else if ( mes == 5 ) printf("May\n"); else if ( mes == 6 ) printf("June\n"); else if ( mes == 7 ) printf("July\n"); else if ( mes == 8 ) printf("August\n"); else if ( mes == 9 ) printf("September\n"); else if ( mes == 10 ) printf("October\n"); else if ( mes == 11 ) printf("November\n"); else printf("December\n"); // Retorna: return rSucesso; } /* Functions definitions: ------------------------- */
the_stack_data/218892639.c
/* ** EPITECH PROJECT, 2019 ** my_compute_power_it ** File description: ** hello */ int my_compute_power_it(int nb, int p) { long int result = nb; if (p == 0) return (1); if (p < 0) return (0); for (int i = 1; i < p; i++){ result *= nb; if (result >= 2147483648 || result < -2147483648) return (0); } return (result); }
the_stack_data/112856.c
// // main.c // SortDemo // // Created by SK on 2020/5/19. // Copyright © 2020 SK_Wang. All rights reserved. // #include <stdio.h> #include <stdlib.h> #define OK 1 #define ERROR 0 #define TRUE 1 #define FALSE 0 #define MAXSIZE 10000 #define N 9 typedef int Status; typedef struct { int r[MAXSIZE + 1]; //用于存储要排序数组,r[0]用作哨兵或临时变量 int length; }SqList; void swap(SqList *L, int i, int j) { int temp = L->r[i]; L->r[i] = L->r[j]; L->r[j] = temp; } void print(SqList L) { int i; for(i = 1; i <= L.length; i++) { printf("%d,", L.r[i]); } printf("\n"); } // 冒泡排序-对顺序表L进行交换排序 void BubbleSort0(SqList *L) { int i, j; for (i = 1; i <= L->length; i++) { for (j = i + 1; j <= L->length; j++) { if (L->r[i] > L->r[j]) { swap(L, i, j); } } } } // 冒泡排序-对顺序表L作冒泡排序 void BubbleSort(SqList *L) { int i, j; for (i = 1; i <= L->length; i++) { for (j = L->length; j > i; j--) { if (L->r[j - 1] > L->r[j]) { swap(L, j - 1, j); } } } } // 冒泡排序-对顺序表L冒泡排序进行优化 void BubbleSort2(SqList *L) { Status flag = TRUE; int i, j; for (i = 1; i <= L->length && flag; i++) { flag = FALSE; for (j = L->length; j > i; j--) { if (L->r[j - 1] > L->r[j]) { swap(L, j - 1, j); flag = TRUE; } } } } // 选择排序--对顺序表L进行简单选择排序 void SelectSort(SqList *L) { int i, j, min; for (i = 1; i <= L->length; i++) { min = i; for (j = i + 1; j <= L->length; j++) { if (L->r[min] > L->r[j]) { min = j; } } if (i != min) { swap(L, i, min); } } } // 直接插入排序算法--对顺序表L进行直接插入排序 void InsertSort(SqList *L) { int i, j; for (i = 2; i <= L->length; i++) { if (L->r[i] < L->r[i - 1]) { L->r[0] = L->r[i]; for (j = i - 1; L->r[0] < L->r[j]; j--) { L->r[j + 1] = L->r[j]; } L->r[j + 1] = L->r[0]; } } } // 希尔排序-对顺序表L希尔排序 void ShellSort(SqList *L) { int i, j; int increment = L->length; do { increment = increment / 3 + 1; for (i = increment + 1; i <= L->length; i++) { if (L->r[i] < L->r[i - increment]) { L->r[0] = L->r[i]; for (j = i - increment; j > 0 && L->r[0] < L->r[j]; j -= increment) { L->r[j + increment] = L->r[j]; } L->r[j + increment] = L->r[0]; } } } while (increment > 1); } /* 大顶堆调整函数; 条件: 在L.r[s...m] 记录中除了下标s对应的关键字L.r[s]不符合大顶堆定义,其他均满足; 结果: 调整L.r[s]的关键字,使得L->r[s...m]这个范围内符合大顶堆定义. */ void HeapAjust(SqList *L, int s, int m) { int j, temp; temp = L->r[s]; for (j = 2 * s; j <= m; j *= 2) { if (j < m && L->r[j] < L->r[j + 1]) { j++; } if (temp >= L->r[j]) { break; } L->r[s] = L->r[j]; s = j; } L->r[s] = temp; } void HeapSort(SqList *L) { int i; for (i = L->length / 2; i > 0; i--) { HeapAjust(L, i, L->length); } for (i = L->length; i > 1; i--){ swap(L, 1, i); HeapAjust(L, 1, i - 1); } } int main(int argc, const char * argv[]) { // insert code here... printf("Hello, 排序算法\n"); int i; // int d[N]={9,1,5,8,3,7,4,6,2}; int d[N] = {50, 10, 90, 30, 70, 40, 80, 60, 20}; SqList l0, l1, l2, l3, l4, l5, l6, l7, l8, l9, l10; for(i = 0; i < N; i++) l0.r[i + 1] = d[i]; l0.length = N; l1 = l2 = l3 = l4 = l5 = l6 = l7 = l8 = l9 = l10 = l0; printf("排序前:\n"); print(l0); printf("\n"); //1.初级冒泡排序 printf("初级冒泡排序:\n"); BubbleSort0(&l0); print(l0); printf("\n"); //2.冒泡排序 printf("冒泡排序:\n"); BubbleSort(&l1); print(l1); printf("\n"); //3.冒泡排序优化 printf("冒泡排序(优化):\n"); BubbleSort2(&l2); print(l2); printf("\n"); //4.选择排序 printf("选择排序:\n"); SelectSort(&l3); print(l3); printf("\n"); //5.直接插入排序 printf("直接插入排序:\n"); InsertSort(&l4); print(l4); printf("\n"); //6.希尔排序 printf("希尔排序:\n"); ShellSort(&l5); print(l5); printf("\n"); printf("堆排序:\n"); HeapSort(&l6); print(l6); printf("\n"); return 0; }
the_stack_data/1123683.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 mark_1 , mark_2 , total; float average; printf("enter your 1st mark "); scanf("%d" , &mark_1); printf("enter your 2nd mark "); scanf("%d" , &mark_2); total = mark_1 + mark_2; average = total/2.0; printf("your average is : %.2f", average); return 0; }
the_stack_data/156394361.c
//Contributors //G. Poppe //Shane Cortez #include <stdlib.h> #include <ctype.h> #include <string.h> #include <time.h> #include <math.h> #include <stdio.h> #include <stdbool.h> void extraCredit(void); void ignoreExtra(void); int choice1(int number); int choice2(char *ptr); int choice3(int number1); void gameRules(); //function to explain rules of room 12 game void gameCraps(); //function to run room 12 game int main(void) { int x,y,z,i,h,g,k,choice=0; char decision; char name[256]; int boxNum=0; // NEEDED FOR ROOM 7: srand(time(NULL)); printf("Please enter your name: "); //Input any number of array inputs scanf("%s",name); printf("Hello %s welcome to the rpgGame!\n",name); while(choice != 99) { puts("You find yourself in a dark room and you are not sure how you got here."); puts("As you look around you see the room has 25 doors, each labeled with a number. You are not sure how such a small room can have 25 doors, sooo magic..."); puts("The room starts filling with water and you must choose a door to open or you will likely drown. you may quit anytime by selecting option 99"); puts("What door do you choose?"); scanf("%d",&choice); switch(choice) { case 1: { int length = 0, num = 0, magicNum = 0; char word[40] = "sacramento"; char *ptr; ptr = word; srand(time(NULL)); length = strlen(name); for(i = 0; i < length;i++) { if(isupper(name[i])) { name[i] = tolower(name[i]); } } name[0] = toupper(name[0]); //Making sure the name is written correctly with uppercase first letter printf("Hello %s, you have entered the room 1.\n", name); puts("You have survived the first part of your adventure..the Drowning.\n"); puts("You have 5 choices to make in order to escape this horror adventure. \n"); printf( "1. You have to solve a math problem for survival. \n" "2. You have to guess the word for survival. \n" "3. You have to find the magic number for survival. \n" "4. Guess the word for survival. \n" "5. Try to make a run for it. \n"); while(choice != 99) { puts("Make a choice(99 to quit): "); scanf(" %d", &choice); switch(choice) { case 1: { puts("You have chosen to solve the math problem. Don't forget you have one chance. Now choose a number between 1-10: "); scanf(" %d", &num); choice1(num); return EXIT_SUCCESS; break; } case 2: { puts("You have chosen to guess the word. What is the capital of California?\n"); choice2(ptr); return EXIT_SUCCESS; break; } case 3: { puts("Enter the magic number(between 1 - 20) from the following math problems: "); magicNum = 1 + rand() % 20; choice3(magicNum); return EXIT_SUCCESS; break; } case 4: { puts("Choice 4."); break; } case 5: { puts("This was the wrong choice to be made. Now you have ended up in a room with nowhere to go...."); return EXIT_SUCCESS; break; } } } break; } case 2: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 3: { while(choice != 99) { printf("%s", "You open the door and find ........\n"); printf("%s", "You see extra credit for CSC 251-01\n Do you chase it?\n"); printf("%s%s%s", "1) To chase it\n","2) Ignore the tempations of passing the class!\n","99) If you don't want to play anymore\n"); scanf("%d",&choice); switch(choice) { case 1: extraCredit(); break; case 2: ignoreExtra(); break; case 99: break; default: printf("%s", "Please follow the directions!\nYou're going to back to spawn!\n"); break; } break; } break; } case 4: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 5: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 6: { while(choice != 99) { } break; } case 7: { int enteredRoom = 0; int chestLocked = 0; char chestInventory[4][25] = {"bottle of rum", "dead cricket", "odd device"}; char playerInventory[4][25] = {"", "", "", ""}; int count = 0; // 0 is locked, 1 is open. char item[25]; int bottle = 3; while(choice != 99) { if(enteredRoom == 0) { puts("You quickly grab the door knob and open the 7th door. The water causes you to fall and forces you into the room. You immediately get to your feet and grab the door nob from the inside and turn it. It's jammed! Clearly the water must be forcing it closed."); enteredRoom++; } if(bottle == 3) { puts("You scan the room and find a large chest at the foot of an old bed. You also find a small table near the right side of the bed with a dusty old book and a bottle of rum. "); } else { puts("You scan the room and find a large chest at the foot of an old bed. You also find a small table near the right side of the bed with a dusty old book. "); } puts("***********************************************"); puts("At this point you have 3 choices:"); puts(""); puts("1. Examine the chest."); if(bottle == 3) { puts("2. Approach the small table and examine the book next to the bottle of rum."); } else if((bottle > 0)) { puts("2. Have another swig of that bottle on the small table. Hell, you don't even notice the book right next to it at this point."); } else { puts("2. Approach the small table and examine the book."); } puts("3. Take a nap."); puts(""); puts("What do you choose?"); scanf("%d",&choice); if(choice == 1) { if(chestLocked == 0) { puts("***********************************************"); puts("You walk over to the dark end of the room and approach the chest near the foot of the bed. It is made mostly of oak with broad iron bands reinforcing it. You jiggle the clasp but it appears to be locked."); puts(""); } else { puts("***********************************************"); puts("You open the chest and see the following:"); for(count; count < 3; count++) { printf("%d. %s \n", count +1, chestInventory[count]); } puts("4. Close the chest."); puts("Select an item number to add it to your inventory, or simply close the chest."); scanf("%d",&choice); /* Insert code for moving item from the chest to the players inventory. (if logic) */ } } else if(choice == 2) { if(bottle == 3) { puts("***********************************************"); puts("You approach the small table near the bed and pick up the book. It's a bit dusty with faded red lettering accross the cover. The title of the book is, 'Diary'."); puts(""); puts("You open the book, and sift through the crumpled pages. It appears to be giberish full of what looks like complex equations and symbols. You move to the last page and you see a sketch for an odd looking device. At the header, the page reads, 'Odd Device!'. In the print below the sketch is a somewhat cryptic statement:'"); puts(""); puts("'Only this 'odd device' will get you out of this room. But there is huge risk in using it, so I locked it away.'"); puts(""); puts("After reading the book, you grab the bottle of rum, pop the cork and take a huge swig!"); puts(""); } else { puts(""); } // Random drunk behavior! x = 1 + rand()%10; if((x <= 5) && (bottle > 0)) { if(bottle != 3) { puts("***********************************************"); } if(bottle == 3) { puts("Ahhh! Good stuff. You have a compelling desire for another drink. Maybe you have a problem."); bottle--; } else { puts("Mmm, this must be spiced rum. You can't resist another drink."); bottle--; } } else if (((x > 5) && (x < 10)) && (bottle > 0)) { if(bottle != 3) { puts("***********************************************"); } else { puts(""); } puts("The rum is already starting to hit you. You begin to feel light headed."); bottle--; } else if ((x == 10) || (bottle == 0)) { if(bottle != 3) { puts("***********************************************"); } else { puts(""); } puts("Damn! The rum is powerful stuff. You begin to feel dizzy. You find yourself having a difficult time standing. You have a compelling desire to sing. As you contemplate what the words are to that song vaguely in your head. You stumble, fall, knocking your head on the edge of the table."); puts(""); puts("....a day passes...."); puts(""); puts("Your eyes slowly open. Wow, what a headache! Slowly your eyes begin to come into focus. You realize you are laying on the floor on the side of the bed. Under the bed you can see the empty bottle tipped over. Something near it catches your eye."); puts(""); puts("Next to the bottle you see a small rusted looking key."); bottle = 0; playerInventory[0] == "key"; } else { puts("There's really nothing more for you at this table. Move on..."); } } else if(choice == 3) { puts("***********************************************"); puts("It's been a long day. *yawn* After an hour or so of sleep, something wakes you up! Oh yes! There's an unexplained flood in the room outside of your jammed door."); puts(""); puts("You jump out of bed, with a clearer mind. The rest did you well. You vaguely recall a dream about having read the dusty old book on the table next to you."); puts(""); } else { puts("wrong choice"); puts(""); } } // Need to code an exit out of the loop for room 7 } case 8: { while(choice != 99) { puts("Erick Vargas' Door\n"); //I'll remove this once we submit the final product, it's just a reminder for me puts("You enter door 8 and you find yourself on a tropical island. You see a small group of people running around collecting materials, what do you do?\n"); printf("1) Introduce yourself 2) Ask where you are 3) Just watch them 4) Ignore them 5) Try to avoid them\n"); scanf("%d",&choice); switch(choice) { case 1: { while(choice != 99) { puts("You walk up to them and introduce yourself to them, they happily greet you and introduce themselves to you. They ask where you are from, how do you respond?\n"); printf(" choose \n"); //prompt choices about how to answer. scanf("%d",&choice); } break; } case 2: { while(choice != 99) { puts("You walk up to them and ask where you are, they look at you confusingly and tell you that the island your on is named Destiny Island. Still looking confused they ask where you came from, how do you respond?"); printf(" choose \n"); //prompt choices about how to answer. scanf("%d",&choice); } break; } case 3: { while(choice != 99) { puts("From a distance you stay watching them, you just see that they continue running around collecting materials for some reason. As you keep watching them you notice that once they huddled up the girl of the group starts marking off on a checklist. You start to wonder more what they're trying to do, what do you do?"); printf(" choose \n"); //prompt choices about what to do. scanf("%d",&choice); } break; } case 4: { while(choice != 99) { puts("You decide to just ignore them, what do you do instead?"); printf(" choose \n"); //prompt choices about what to do instead scanf("%d",&choice); } break; } case 5: { while(choice != 99) { puts("Panicked, you decide to hide from them. Where do you choose to hide?"); printf(" choose \n"); //prompt choices of where to hide scanf("%d",&choice); } break; } } break; } } case 9: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 10: { while(choice != 99) { puts("you open the door and find ........"); puts("A lottery machine?"); puts("Welcome to Fabian's room"); int n1,n2,n3,newrn1,newrn2,newrn3; bool checkNum1; bool checkNum2; bool checkNum3; srand(time(NULL)); printf("Enter the lottery by entering three numbers. Each 1 digit\n"); scanf(" %d %d %d",&n1,&n2,&n3); newrn1 = rand()%10; newrn2 = rand()%10; newrn3 = rand()%10; printf("Your numbers are: %d, %d, %d\n",n1,n2,n3); printf("The winning lottery numbers are: %d, %d, %d\n",newrn1,newrn2,newrn3); if(n1==newrn1 || n1==newrn2 || n1==newrn3) { checkNum1= true; } else { checkNum1=false; } if(checkNum1) { if (n1==newrn1) { newrn1=420; } else if (n1==newrn2) { newrn2=420; } else { newrn3=420; } } if(n2==newrn1 || n2==newrn2 || n2==newrn3) { checkNum2= true; } else { checkNum2=false; } if(checkNum2) { if (n2==newrn1) { newrn1=420; } else if (n2==newrn2) { newrn2=420; } else { newrn3=420; } } if(n3==newrn1 || n3==newrn2 || n3==newrn3) { checkNum3= true; } else { checkNum3=false; } if(checkNum3) { if (n3==newrn1) { newrn1=420; } else if (n3==newrn2) { newrn2=420; } else { newrn3=420; } } if(checkNum1 && checkNum2 && checkNum3) { if(n1==newrn1 && n2==newrn2 && n3==newrn3) { printf("You've hit the jackpot of 1,000,000\n"); } else { printf("You wont 1,000\n"); } } else if ((checkNum1 && checkNum2 || checkNum1 && checkNum3) || (checkNum2 && checkNum3)) { printf("You've won $100\n"); } else if (checkNum1 || checkNum2 || checkNum3) { printf("You won $10\n"); } else { printf("You won nothing sorry!\n"); } puts("choose a new room now if you dare... \n"); scanf("%d",&choice); } break; } case 11: { while(choice != 99) { } break; } case 12: { while(choice != 99) { puts("you open the door and find you've entered room 12........\n"); char response, temp; //char variables needed for game to work { printf("Since you're here and brave, will you take a chance and play a game of cards? Enter 'y' twice for yes or '99' to leave at any time...\n"); response = getchar(); //set response to equal user's input temp = getchar(); //set temp value to equal user's input if(response == 'y' || response == 'Y') //if answer is equal to letter 'y' or 'Y'... { gameRules(); //simple function that prints game rules for user before game begins gameCraps(); //calls main game function } else if(response == 99) //had issues modifying this code to run no...using escape 99 for now to to exit game... { puts("You don't want to play, but you'll be back. Goodbye for now... >:D"); break; } } scanf("%d", &choice); //scan in user's input for choice... } break; } case 13: { while(choice != 99) { puts("As your hand reaches for the 13th door you think about all the superstitions related to the number 13."); puts("However, you open it anyways and you find yourself in a large dark room that is immedietly cold and nothing is visible."); puts("Although the room is pitch black you cant even see your hands, you stop and look to your right when something catches your eye."); puts("A samll bright light is floating in the distance, close enough to see but far enough to not be able to know what it is."); puts("Do you walk towards the light or do you wak in the opposite direction."); puts("1. Walk towards the light."); puts("2. Walk in the other direction."); scanf("%d",&choice); if(choice == 1) { puts("feeling curious you walk towards the light."); puts("As your walking, the light gets brighter and slowly getting closer until you feel a sudden rush of cold air on your left shoulder."); puts("You look over and see a ghost like hand resting on your shoulder"); printf("It whispers into your ear with a low grungy voice \"%s turn around, I can give you anything you want \" \n",name); puts("Do you turn around or keep walking towards the light?"); puts("1. Continue walking towards the light."); puts("2. Turn around and face this mysterious voice"); scanf("%d", &choice); if(choice == 1) { puts("Overcoming your curiosity once more, you continue walking towards the light,"); puts("As you get closer to the light you can now see a forest and wonder if this is the way out."); puts("However, you once more hear this voice different from before."); } break; } else if(choice == 2) { puts("Not knowing what this light could be you decide to turn around and head deeper into the unknown darkness."); puts("...more to come..."); break; } else { puts("Wrong choice"); } } break; } case 14: {//Velasco,Jesse srand(time(NULL)); //Room 1 //Magic Number int mn = 7; //Universal Response variable int response; //Room 2 int ClassScores = 1 + rand()%10; int a,b,c,d,f; //Room 3 int counter = 0; int one,two,three,four,five,six; int number = 0; int guess = 0; while(choice != 99) { printf("Desperately.You push door 14 open\n"); printf("Once inside you bear your entire weight against the door to slam it shut.\n"); printf("Recuperated you look around to find a door with an inscription attached to it via a wooden tablet fixated above the archway\n"); printf("Its a game.\n"); printf("Guess the magic number and you'll be allowed passage. Fail.Passage to the underworld will be granted instead\n"); printf("Welp.Time to take your shot.Good luck.\n"); printf("Enter a number between 1 and 10\n"); scanf("%d", &response); while(response < 1 || response > 10) { printf("Please enter a number between 1 and 10 inclusively\n"); scanf("%d",&response); } printf("%d + magic number = %d\n",response,(response + mn)); printf("%d * magic number = %d\n",response,(response * mn)); printf("%d - magic number = %d\n",response,(response - mn)); printf("What is your guess? It states.\n"); scanf("%d",&response); if(response == mn) { printf("You are correct! The door opens. You pass through with no issues.\n"); } else { printf("Oh no. You guessed wrong.\n"); printf("The ceiling begins to lower. Looks like its game over.\n"); printf("Thanks for playing!\n"); exit(0); } //Room 2 printf("You enter an empty classroom.\n"); printf("A monitor begins to lower from the ceiling.\n"); printf("\"Samsung\" you notice. Nice.\n"); printf("On the screen a grading scale is shown.\n"); printf("A = 4.0, B = 3.0, C = 2.0, D = 1.0,F = 0\n"); printf("There are %d A's\n", a = 1 + rand()%10); printf("There are %d B's\n", b = 1 + rand()%10); printf("There are %d C's\n", c = 1 + rand()%10); printf("There are %d D's\n", d = 1 + rand()%10); printf("What is the average?\n"); scanf("%d",&response); if(response == ((a*4) + (b*3) + (c*2) + (d*1) + (f*0))) { printf("Like a teacher you graded it! Nice job!\n"); printf("The room walls begin to shake as the one in front of you begins to open up. Revealing a secret tunnel.\n"); printf("You push on.\n"); } else { printf("Looks like this is where you dropout.\n"); printf("Thanks for playing!\n"); exit(0); } //Room 3 HAS BUG printf("As you exit the tunnel you find yourself in a casino\n"); printf("Oddly enough there is only one table with a single seat directly ahead of you.\n"); printf("You approach the table cautiously. The dealer says \"Do not be afraid. I will only take what you are willing to give\" he laughs. Try your luck.\n"); printf("The game is simple. Pick a number and guess the number of times that number will be rolled. The die will be rolled 10 times.\n"); printf("\"What are you willing to bet?\" asks the dealer.\n"); printf("Having nothing of value you bet what you have. Your life. A true gambler at heart.\n"); printf("\"Very well. I accept your bet. \"\n"); for(int i = 0 ; i < 10 ; i++) { counter = 1 + rand()%6; switch(counter) { case 1: one += 1; break; case 2: two += 1; break; case 3: three += 1; break; case 4: four += 1; break; case 5: five += 1; break; case 6: six += 1; break; } } printf("Now state the number you would like to bet on between 1 and 6.\n"); scanf("%d",&number); if(number < 1 || number >6) { printf("Please pick a number between 1 and 6 for your bet.\n"); scanf("%d",&number); } switch(number) { case 1: printf(" Now guess how many times that number has been rolled. You have a rage of 1 above and below the number. Good luck!\n"); scanf("%d",&guess); if(guess >= (one - 1) || guess <= (one + 1)) { printf("Your guess: %d\n", guess); printf("# of rolls: %d\n",one); printf("You win! You get to keep your life ,and get passage on.\n"); } else { printf("I'm afraid you'll be cashing out now.\n"); printf("Thanks for playing!\n"); exit(0); } case 2: printf(" Now guess how many times that number has been rolled. You have a rage of 1 above and below the number. Good luck!\n"); scanf("%d",&guess); if(guess >= (two - 1) || guess <= (two + 1)) { printf("Your guess: %d\n", guess); printf("# of rolls: %d\n",two); printf("You win! You get to keep your life ,and get passage on.\n"); } else { printf("I'm afraid you'll be cashing out now.\n"); printf("Thanks for playing!\n"); exit(0); } case 3: printf(" Now guess how many times that number has been rolled. You have a rage of 1 above and below the number. Good luck!\n"); scanf("%d",&guess); if(guess >= (three - 1) || guess <= (three + 1)) { printf("Your guess: %d\n", guess); printf("# of rolls: %d\n",three); printf("You win! You get to keep your life ,and get passage on.\n"); } else { printf("I'm afraid you'll be cashing out now.\n"); printf("Thanks for playing!\n"); exit(0); } case 4: printf(" Now guess how many times that number has been rolled. You have a rage of 1 above and below the number. Good luck!\n"); scanf("%d",&guess); if(guess >= (four - 1) || guess <= (four + 1)) { printf("Your guess: %d\n", guess); printf("# of rolls: %d\n",four); printf("You win! You get to keep your life ,and get passage on.\n"); } else { printf("I'm afraid you'll be cashing out now.\n"); printf("Thanks for playing!\n"); exit(0); } case 5: printf(" Now guess how many times that number has been rolled. You have a rage of 1 above and below the number. Good luck!\n"); scanf("%d",&guess); if(guess >= (five - 1) || guess <= (five + 1)) { printf("Your guess: %d\n", guess); printf("# of rolls: %d\n",five); printf("You win! You get to keep your life ,and get passage on.\n"); } else { printf("I'm afraid you'll be cashing out now.\n"); printf("Thanks for playing!\n"); exit(0); } case 6: printf(" Now guess how many times that number has been rolled. You have a rage of 1 above and below the number. Good luck!\n"); scanf("%d",&guess); if(guess >= (six - 1) || guess <= (six + 1)) { printf("Your guess: %d\n", guess); printf("# of rolls: %d\n",six); printf("You win! You get to keep your life ,and get passage on.\n"); } else { printf("I'm afraid you'll be cashing out now.\n"); printf("Thanks for playing!\n"); exit(0); } } printf("To be cont.\n" ); } break; } case 15: { while(choice != 99) { } break; } case 16: { while(choice != 99) { } break; } case 17: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 18: { while(choice != 99) { } break; } case 19: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 20: { int level = 0,attack = 0,magic = 0,health = 0,defense = 0,totalHP = 0; bool NEW = true; srand(time(NULL)); while(choice != 99) { /*puts("you open the door and find ........"); scanf("%d",&choice);*/ bool gameLoop = false; int option = 0; int levelF = level; int healthPOT = 3; int damage = 0; bool magician = false; bool warrior = false; bool loss = false; int multiplier = 0; char goblin[10] = "Goblin"; char zombie[10] = "Zombie"; char giant[10] = "Giant"; char highSumm[25] = "High Summoner"; char quetzal[25] = "God Quetzalcoatl"; char goblinATT[50] = "The Goblin takes his tiny shiv and cuts you."; char zombieATT[50] = "The Zombie lunges forward and bites you."; char giantATT[80] = "The Giant takes his club and strikes you in the chest"; char highATT[100] = "The High Summoner casts a large cloud above you and calls down a bolt of lightning."; char quetzalATT[100] = "Quetzalcoatl, The Creator, blasts you with a blue stream of fire."; while(NEW) { puts("Pick your class."); puts("_________________________________________"); puts("1. Warrior."); puts("2. Magician."); puts("3. Exit."); scanf(" %d",&option); switch(option) { case 1: level = 1; attack = 5; magic = 1; health = 15; defense = 2; totalHP = 15; warrior = true; puts("You have selected Warrior."); gameLoop = true; NEW = false; break; case 2: level = 1; attack = 1; magic = 10; health = 10; totalHP = 10; defense = 1; magician = true; puts("You have selected Magician."); gameLoop = true; NEW = false; break; case 3: gameLoop = false; puts("Heading back to the main menu!"); NEW = false; break; default: puts("Please select a valid option"); break; }; } if(gameLoop==false) break; levelF = level; if(gameLoop == true) puts("You will be given 3 health potions that heal \"20%\" of your health.\nUse them wisely."); puts("_________________________________________"); puts(""); for(levelF; ((gameLoop == true)&&(levelF <= 5)); levelF++) { int monsterHP = 8; int monsterATT = 5; multiplier = levelF*3; if(warrior == true) { totalHP += multiplier; health += multiplier; attack += multiplier; defense += (multiplier/3); } else if(magician == true) { totalHP +=(3*(multiplier/2)); health +=(3*(multiplier/2)); magic += (multiplier+8); defense += (multiplier/4); } else puts("Something went wrong with warrior/magician boolean"); monsterHP+=(multiplier*2); monsterATT+=(multiplier*2); while(monsterHP > 0) { if(levelF==1) printf("%s HP: %d DMG: %d \n", goblin,monsterHP,monsterATT); else if(levelF==2) printf("%s HP: %d DMG: %d \n", zombie,monsterHP,monsterATT); else if(levelF==3) printf("%s HP: %d DMG: %d \n", giant,monsterHP,monsterATT); else if(levelF==4) printf("%s HP: %d DMG: %d \n", highSumm,monsterHP,monsterATT); else if(levelF==5) printf("%s HP: %d DMG: %d \n", quetzal,monsterHP,monsterATT); else puts("Something went wrong calculating string name."); if(warrior == true) printf("Warrior: %s HP: %d DMG: %d \n",name,health,attack); else printf("Magician: %s HP: %d DMG: %d \n",name,health,magic); puts("_________________________________________"); puts("1. Attack."); puts("2. Magic."); puts("3. Health Potion."); scanf(" %d",&option); int charATT = (rand()%attack); int charMAG = (rand()%magic); switch(option) { case 1: printf("You've attacked for %d.\n",charATT); monsterHP -= charATT; break; case 2: printf("You've attacked for %d.\n",charMAG); monsterHP -= charMAG; break; case 3: if(healthPOT <= 0) { puts("You have no more potions left!"); break; } else { health +=(.20*(totalHP)); healthPOT--; } break; default: break; }; if(monsterHP > 0) { damage = ((rand()%monsterATT) - defense); if(damage > 0) { if(levelF==1) printf("%s\n", goblinATT); else if(levelF==2) printf("%s\n", zombieATT); else if(levelF==3) printf("%s\n", giantATT); else if(levelF==4) printf("%s\n", highATT); else if(levelF==5) printf("%s\n", quetzalATT); else puts("Something went wrong calculating attack string."); health -= damage; printf("You took %d damage.\n",damage); } else puts("Their attempt to attack you has failed."); } else { if(levelF==1) printf("You have defeated the %s\n",goblin); else if(levelF==2) printf("You have defeated the %s\n",zombie); else if(levelF==3) printf("You have defeated the %s\n",giant); else if(levelF==4) printf("You have defeated the %s\n",highSumm); else if(levelF==5) printf("You have defeated the %s\n",quetzal); else puts("Something went wrong calculating the defeat string."); } if(health<=0) { puts("You lose."); loss=true; break; } puts("________________________________________________________________"); } if(loss == true) gameLoop=false; level = levelF; } if(level==5&&health>0) printf("Congratulations %s, you defeated all the bosses in Room 20!\n",name); puts("________________________________________________________________"); } break; } case 21: //Michael Morgan's room { while(choice != 99) { puts("you open the door and find ........"); puts("A penguin drinking a been"); scanf("%d",&choice); } break; } case 22: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 23: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 24: { #include <time.h> int choice = 0, turn = 0, bananaAmount = 0, orangeAmount = 0; puts("As you open the door, you notice a sign reading: \"This is Phillip F. Aguilera's room\".\n" "You enter the room and close the door behind you, noticing the choice of more doors. There are three more doors to choose.\n" "A sheet of paper is lying on the floor. You pick it up and begin to read what has been written.\n" "It states:\n"); printf("You have %d bananas and %d oranges.\n", bananaAmount, orangeAmount); puts("Enter the rooms and try to escape with the highest amount of bananas and oranges as possible!\n"); puts("You must have XXX amount of bananas and oranges in XXX amount of turns or you lose!\n"); for (turn = 0; turn < 4; turn++) { puts("Main Menu:\n" "1) Enter Room 1.\n" "2) Enter Room 2.\n" "3) Enter Room 3.\n"); printf("Enter the Room you wish to enter: "); scanf("%d", &choice); switch(choice) { case 1: puts("You are in Room 1.\n"); break; case 2: puts("You are in Room 2.\n"); break; case 3: puts("You are in Room 3.\n"); } } while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 25: { while(choice != 99) { printf("Room for Richmond Laureta AKA (rlaureta)\n"); /*ROUGH DRAFT OF MY GAME: The title of my game is: "The King's Tyrant" I will create an rpg game that will start in a ruined dungeon and you wake up from your sleep. You then go and pick your class and weapon. You can either be a warrior or mage class. Then you pick your weapon and your path. You will also have skills and you will spend points to level them up when you gain experience. My game will have a karma effect for good and bad. The more you choose to be bad the choices will be more bad. If you choose to be good then your path will be more good. Its up to you who you want to be. At the end of the game you will see what you become.*/ puts("You open the door and close it behind you."); puts("After you overcome the panic from almost drowning, you look around and You find yourself in a cave, the air is damp and you smell mold."); puts("You notice a skeleton at your feet with it's right hand clenched around something. The cave ahead leads to a tunnel and you see a door to your right."); puts("At this point you have 3 choices:"); puts("1. Examine the skeleton."); puts("2. Proceed further ahead in the cave."); puts("3. Enter the door to your right."); scanf("%d",&choice); if(choice == 1) { puts("You reach down and pry open the skeleton's hand, a finger breaks loose and you place it in your pocket. Once you pry the opject free you look at it closely in the light and see it is a live grenade and the pin springs free. You drop the grenade and dash through the cave. You can hear the grenade explode, collapsing the tunnel behind you."); puts("To be continued..."); break; } else if(choice == 2) { puts("You find yourself further ahead in the cave."); puts("To be continued...."); break; } else if(choice == 3) { puts("You enter the and close the door behind you."); printf("You hear an loud voice \" %s why do you disturb me? \" \n",name); puts("To be continued...."); break; } else { puts("wrong choice"); } } break; } case 26: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 27: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 28: { //Room #28 for Shane Cortez while (choice != 99) { srand(time(NULL)); int randNum=rand()%2; puts("you enter the room marked 28"); puts("As the panic of drowning subsides you look up to notice that the room is shaking and the ground splitting in half revealing a pit to nothingness you have to act fast or risk missing the jump across!"); puts("What do you do:"); puts("1. JUMP!"); puts("2. Quickly look around and reassess the situation"); puts("99. At any time to End Game"); scanf("%d", &choice); if (choice == 1) { puts("in a panic you jump across the pit and make it safely to the other side."); puts("As you made your jump you noticed that there was a key dangling on a string over the midde of the pit, but missed your opportunity to grab it."); puts("As you look around you notice a door sealed shut by vines, and there is a locked chest right next to it"); puts("You suspect that the key will open the chest, but you have to get it first..."); puts("What do you do:"); puts("1. Try to jump across and jump back to grab the key"); puts("2. Check inventory"); scanf("%d", &choice); if (choice == 1) { puts("You attempt the first jump and realize too late that the pit is far too wide to jump across, you fall into the darkness and are never seen again...."); puts("Game Over"); choice = 99; break; } else if (choice == 2) { puts("you check your inventory and notice that you packed your trusty hook attached to a long stick, you can use this to get the key."); puts("you reach across the pit with your hook and grab the key, unfortunatly in the action you drop the hook while just barely being able to hang onto the key"); puts("You say your farewells to the hook and put the key in your inventory."); puts("Key added to inventory"); puts("You are now faced with a locked chest and a vine covered door"); puts("What do you do:"); puts("1. inspect door."); puts("2. open chest with key"); scanf("%d", &choice); if (choice == 1) { puts("upon further inspection you notice that the vines appear flamable..."); puts("you then turn your attention to the chest, you pull out the key and unlock the chest, inside you find a scroll which reads:"); puts("write a spell and this scroll will grant you power..."); puts("Unfortunately you only studied one year of spellcasting in highschool and the only three spells you remember from back then are:"); puts("1. fire"); puts("2. water"); puts("3. earth"); puts("What will you write:"); scanf("%d", &choice); if (choice == 1) { puts("you write the ancient runes of fire onto the page."); puts("The scroll flashes bright red with fiery power, suddenly your hands begin to feel hot, when suddenly they light ablaze! with this power you can shoot fire out of your hand!"); puts("You strike an agressive pose and engulf the vine covered door in flames."); puts("As the fire and smoke subside, the door sits ajar with a light shining through."); puts("What will you do:"); puts("1. walk through the door"); puts("2. Turn around and jump into the pit"); scanf("%d", &choice); if (choice == 1) { //Victory! puts("You open the door and are blinded by light, as your vision returns you realize you are in the middle of nowhere in the desert, and the door magically dissapears"); puts("You escaped, but now what?"); puts("Congrats you finished the game. Thank you for playing!"); choice = 99; break; } else if (choice == 2) { puts("I'm not sure why you chose this, but you turn around and jump into the pit, you are never seen again...."); puts("Game Over..."); choice = 99; break; } } else if (choice == 2) { puts("You write down the ancient runes of water onto the page."); puts("the scroll glows a conforting blue color, suddenly your hands feel damp, you can now use this on the door."); puts("You ready yourself and shoot a powerful stream of water on the vines."); puts("You stare at the vines as they grow greener and stronger from the water, the vines then grow at a rapid rate engulfing the narrow walkway that you stand on."); puts("You find yourself losing balance on the decreasing surface, eventually falling into the pit..."); puts("You are never seen again..."); puts("Game Over"); choice = 99; break; } else if (choice == 3) { puts("You write the ancient rune of earth."); puts("suddenly the scroll glows emerald green, as your hands begin to feel one with the earth, you can use this on the door."); puts("You ground yourself, and use your new powers on the vines."); puts("To your suprise, the earth spell you wrote only makes the vines stronger, so much so that they begin to grow wildly out of control!"); puts("The vines begin to take up most of the surface you stand on..."); puts("You find yourself losing balance on the decreasing space, eventually falling into the pit..."); puts("You are never seen again..."); puts("Game Over"); choice = 99; break; } } else if (choice == 2) { puts("you turn your attention to the chest, you pull out the key and unlock the chest, inside you find a scroll which reads:"); puts("write a spell and this scroll will grant you power..."); puts("Unfortunately you only studied one year of spellcasting in highschool and the only three spells you remember from back then are:"); puts("1. fire"); puts("2. water"); puts("3. earth"); puts("What will you write:"); scanf("%d", &choice); if (choice == 1) { puts("you write the ancient runes onto the page."); puts("The scroll flashes bright red with fiery power, suddenly your hands begin to feel hot, when suddenly they light ablaze! with this power you can shoot fire out of your hand!"); puts("You strike an agressive pose and engulf the vine covered door in flames."); puts("As the fire and smoke subside, the door sits ajar with a light shining through."); puts("What will you do:"); puts("1. walk through the door"); puts("2. Turn around and jump into the pit"); scanf("%d", &choice); if (choice == 1) { //Victory! puts("You open the door and are blinded by light, as your vision returns you realize you are in the middle of nowhere in the desert, and the door magically dissapears"); puts("You escaped, but now what?"); puts("Congrats you finished the game. Thank you for playing!"); choice = 99; break; } else if (choice == 2) { puts("I'm not sure why you chose this, but you turn around and jump into the pit, you are never seen again...."); puts("Game Over..."); choice = 99; break; } } else if (choice == 2) { puts("You write down the ancient runes of water onto the page."); puts("the scroll glows a conforting blue color, suddenly your hands feel damp, you can now use this on the door."); puts("You ready yourself and shoot a powerful stream of water on the vines."); puts("You stare at the vines as they grow greener and stronger from the water, the vines then grow at a rapid rate engulfing the narrow walkway that you stand on."); puts("You find yourself losing balance on the decreasing surface, eventually falling into the pit..."); puts("You are never seen again..."); puts("Game Over"); choice = 99; break; } else if (choice == 3) { puts("You write the ancient rune of earth."); puts("suddenly the scroll glows emerald green, as your hands begin to feel one with the earth, you can use this on the door."); puts("You ground yourself, and use your new powers on the vines."); puts("To your suprise, the earth spell you wrote only makes the vines stronger, so much so that they begin to grow wildly out of control!"); puts("The vines begin to take up most of the surface you stand on..."); puts("You find yourself losing balance on the decreasing space, eventually falling into the pit..."); puts("You are never seen again..."); puts("Game Over"); choice = 99; break; } } } } else if (choice == 2) { puts("As you look around frantically you notice a chest on the other side next to a door and a key dangling over the ever growing death pit on a string.... now is the time to jump"); puts("As you make your jump you take the time to aim for grabbing the key on the way over.... It's going to be close, lets see if you can make it."); if (randNum == 0) { puts("You leap through the air and grab the other side, when suddenly the ledge gives way, leaving you to fall into the darkness never to be seen again...."); puts("Game Over"); choice = 99; break; } else { puts("You jump with all your might, and land on the other side barely missing the fall by an inch."); } if (randNum == 1 && choice == 2) { puts("You made it across! now before you sits a door closed off by vines and a locked chest that you suspect will be unlocked by the key..."); puts("What is your next move:"); puts("1. Open the chest"); puts("2. Further inspect the door"); scanf("%d", &choice); if (choice == 1) { puts("upon further inspection you notice that the vines appear flamable..."); puts("you then turn your attention to the chest, you pull out the key and unlock the chest, inside you find a scroll which reads:"); puts("write a spell and this scroll will grant you power..."); puts("Unfortunately you only studied one year of spellcasting in highschool and the only three spells you remember from back then are:"); puts("1. fire"); puts("2. water"); puts("3. earth"); puts("What will you write:"); scanf("%d", &choice); if (choice == 1) { puts("you write the ancient runes of fire onto the page."); puts("The scroll flashes bright red with fiery power, suddenly your hands begin to feel hot, when suddenly they light ablaze! with this power you can shoot fire out of your hand!"); puts("You strike an agressive pose and engulf the vine covered door in flames."); puts("As the fire and smoke subside, the door sits ajar with a light shining through."); puts("What will you do:"); puts("1. walk through the door"); puts("2. Turn around and jump into the pit"); scanf("%d", &choice); if (choice == 1) { //Victory! puts("You open the door and are blinded by light, as your vision returns you realize you are in the middle of nowhere in the desert, and the door magically dissapears"); puts("You escaped, but now what?"); puts("Congrats you finished the game. Thank you for playing!"); choice = 99; break; } else if (choice == 2) { puts("I'm not sure why you chose this, but you turn around and jump into the pit, you are never seen again...."); puts("Game Over..."); choice = 99; break; } } else if (choice == 2) { puts("You write down the ancient runes of water onto the page."); puts("the scroll glows a conforting blue color, suddenly your hands feel damp, you can now use this on the door."); puts("You ready yourself and shoot a powerful stream of water on the vines."); puts("You stare at the vines as they grow greener and stronger from the water, the vines then grow at a rapid rate engulfing the narrow walkway that you stand on."); puts("You find yourself losing balance on the decreasing surface, eventually falling into the pit..."); puts("You are never seen again..."); puts("Game Over"); choice = 99; break; } else if (choice == 3) { puts("You write the ancient rune of earth."); puts("suddenly the scroll glows emerald green, as your hands begin to feel one with the earth, you can use this on the door."); puts("You ground yourself, and use your new powers on the vines."); puts("To your suprise, the earth spell you wrote only makes the vines stronger, so much so that they begin to grow wildly out of control!"); puts("The vines begin to take up most of the surface you stand on..."); puts("You find yourself losing balance on the decreasing space, eventually falling into the pit..."); puts("You are never seen again..."); puts("Game Over"); choice = 99; break; } } else if (choice == 2) { puts("you turn your attention to the chest, you pull out the key and unlock the chest, inside you find a scroll which reads:"); puts("write a spell and this scroll will grant you power..."); puts("Unfortunately you only studied one year of spellcasting in highschool and the only three spells you remember from back then are:"); puts("1. fire"); puts("2. water"); puts("3. earth"); puts("What will you write:"); scanf("%d", &choice); if (choice == 1) { puts("you write the ancient runes onto the page."); puts("The scroll flashes bright red with fiery power, suddenly your hands begin to feel hot, when suddenly they light ablaze! with this power you can shoot fire out of your hand!"); puts("You strike an agressive pose and engulf the vine covered door in flames."); puts("As the fire and smoke subside, the door sits ajar with a light shining through."); puts("What will you do:"); puts("1. walk through the door"); puts("2. Turn around and jump into the pit"); scanf("%d", &choice); if (choice == 1) { //Victory! puts("You open the door and are blinded by light, as your vision returns you realize you are in the middle of nowhere in the desert, and the door magically dissapears"); puts("You escaped, but now what?"); puts("Congrats you finished the game. Thank you for playing!"); choice = 99; break; } else if (choice == 2) { puts("I'm not sure why you chose this, but you turn around and jump into the pit, you are never seen again...."); puts("Game Over..."); choice = 99; break; } } else if (choice == 2) { puts("You write down the ancient runes of water onto the page."); puts("the scroll glows a conforting blue color, suddenly your hands feel damp, you can now use this on the door."); puts("You ready yourself and shoot a powerful stream of water on the vines."); puts("You stare at the vines as they grow greener and stronger from the water, the vines then grow at a rapid rate engulfing the narrow walkway that you stand on."); puts("You find yourself losing balance on the decreasing surface, eventually falling into the pit..."); puts("You are never seen again..."); puts("Game Over"); choice = 99; break; } else if (choice == 3) { puts("You write the ancient rune of earth."); puts("suddenly the scroll glows emerald green, as your hands begin to feel one with the earth, you can use this on the door."); puts("You ground yourself, and use your new powers on the vines."); puts("To your suprise, the earth spell you wrote only makes the vines stronger, so much so that they begin to grow wildly out of control!"); puts("The vines begin to take up most of the surface you stand on..."); puts("You find yourself losing balance on the decreasing space, eventually falling into the pit..."); puts("You are never seen again..."); puts("Game Over"); choice = 99; break; } } } } choice = 99; break; } } case 29: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 30: { while(choice != 99) { puts("You open the door and find yourself trapped in another room."); puts("In front of you are three buttons: blue, red, yellow."); puts("Lets play a game :)"); puts("Pick a button:"); puts("1.Blue"); puts("2.Red"); puts("3.Yellow"); scanf("%d", &choice); while((choice != 1)&&(choice != 2)&&(choice != 3)&&(choice != 99)) { puts("Enter '1' '2' '3'."); scanf("%d", &choice); } if(choice == 1) { puts("Room 1"); puts("Water starts pouring out from the cieling, this room is starting to flood too!"); puts("You must find a way to stop the water or you will drown, time is running out!"); } if(choice == 2) { puts("Room 2"); puts("Your hear a loud crank, the walls slowly start to close in"); puts("You must find a way to stop the walls, time is running out!"); } if(choice == 3) { puts("A generator turns on, the air begins to get vaccumed out of the room"); printf("You must find a way to stop from suffocating, time is running out!"); } int x=10; while(x!=0) { printf("Timer %d minutes left\n", x); puts("1.Look Around"); puts("2.Use Laptop"); puts("3.Use Tools"); puts("4.Open Door"); scanf("%d", &y); switch(y) { case 1: puts("You look around the room."); puts("The lights in the room are flickering."); puts("In the middle is a big metal crate and ontop is a laptop and small box on it."); puts("One wall has a lot of light switches with a calander next to it."); puts("The calander has the last day circled on the month of december."); puts("The other wall has a lever with a stickynote next to it saying 'hex: FF'."); puts("There is another door in front of you but its locked."); x--; break; case 2: puts("You go up to the laptop and open it up to a terminal"); puts("Please enter code:"); scanf("%d", &z); if(z==1515) { puts("You hear a loud clank, the water stops pouring from the cieling"); } if(z==1231) { puts("A vent opens up in the cieling:"); } if((z!=1515)&&(z!=1231)) { puts("Nothing happened."); } x--; break; case 3: x--; break; case 4: if(y==0) { puts("You have survived and escaped!!"); choice=99; } puts("Door is locked."); x--; break; } } puts("Sorry time ran out and you died"); } break; } case 31: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 32: { while(choice != 99) { puts("Welcome to room 32 where I already know what is on your mind."); puts("I bet I can guess what number your thinking of with just a couple of instructions."); puts("Up for the challenge? y/n"); scanf("%c", &decision); if(decision == 'y') { puts("Pick a number, any number and make sure you remember that number."); puts("Now double the number."); puts("Now add 10 to the new number."); puts("Divide it by 2"); puts("Now subtract that by the original number."); puts("Your new number is now 5"); break; } else if(decision == 'n') { puts("I see you're in no mood for a little fun"); break; } } break; } case 33: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 34: { int flag = 0; while(choice != 99 && flag !=1) { int userchoice;//local variable to store user input. /*Introduction of the game*/ printf("\n"); printf("Welcome to Mythical Island Adventure: you will face certain situations where your character has to make right decision to complete the game. Use your wits to survive the Mythical Island. Good Luck!\n"); printf("Choose the response between entering 1 or 2 whichever will take you further the game. Enter 99 to exit the room 34.\n"); /*game starts*/ /*get valid input from user for decision _1_ and take action based on decision. */ do{ printf("\n");//seperator printf("You start on the journey to come back home to your family for Christmass holiday. Your magical wand transform into a broom stick and fly to the skies. In the middle of the ocean, storm came and broke your broom-stick. You find your self in the middle of the island or so called Mythical Island. What do you do?\n"); printf("1: You make a boat using coconut leaves and try to escape to the ocean.\n"); printf("2: You find and built a shelter using woods and stones.\n"); /*seperator*/ printf("\n"); printf("Your choice: "); scanf(" %d", &userchoice); flag = 1; choice = userchoice;//choice set to userchoice if the user decides to exit _99_. if(userchoice==1) { printf("\n");//seperator printf("The boat is not strong enough and destroyed your journey going to your family celebration in Christmass holiday.\n");//return printf("\n"); printf("Game Over!\n"); printf("\n"); } else if(userchoice == 2) { printf("\n"); printf("Your shelter is built. You start exploring the island...\n"); } else if(userchoice != 1 && userchoice != 2 && choice != 99) { printf("Invalid input! Please enter 1 or 2 only.\n"); } } while(userchoice != 1 && userchoice != 2 &&choice != 99);//to make sure choice isn't _99_. if(choice == 99) break; if(choice != 1)//if they didn't choose _1_, then continue. { do{ //get valid input from the user for decision _2_ and take action based on decision. printf("\n");//separator printf("You see cyclops with their weapons while exploring the forest inside of the island. What do you do?\n"); printf("1: You try to fight and kill the monster using a wood.\n"); printf("2: You quickly hide and secretely go to the other side of the island.\n"); printf("\n");//separator printf("Your choice: "); scanf(" %d", &userchoice); choice = userchoice;//set choice to userchoice if _99_ was read in to exit. if(userchoice==1) { printf("\n"); printf("You became cyclops lunch, they said you are yummy and thank you for the meal.\n"); printf("\n"); printf("Game Over!\n"); printf("\n"); break;//I am using my void main to exit in the game only. } else if(userchoice==2) { printf("\n"); printf("You found fruits and coconut juice. You go back to your shelter and ate them to fight another day...\n"); } else if(userchoice != 1 && userchoice != 2 && choice != 99) { printf("Invalid input! Please enter 1 or 2 only.\n"); } } while(userchoice !=1 && userchoice !=2 && choice != 99); if(choice == 99) break; /*if choice wasn't _1_, they are still in the game. */ if(choice != 1) { do{ //get valid input from user for decision _3_ and take action based on decision. printf("\n"); //separator printf("By exploring yesterday, you found out cyclops looks big and strong, and trolls looks small and weak. What do you do?\n"); printf("1: You approach the friendly trolls.\n"); printf("2: You approach cyclops to align yourself with powerful forces not sure their instention though.\n"); printf("\n"); printf("Your choice: "); scanf(" %d", &userchoice); choice = userchoice; //set choice to userchoice to see if _99_ was read in to exit. if(userchoice==1) { printf("\n"); printf("The trolls are indeed friendly they invite you to their home, so your not alone anymore.\n"); } else if(userchoice==2) { printf("\n"); //separator printf("You try to communicate with cyclops. They get angry and attack you because their hunting prey got escape.\n"); printf("\n"); printf("Game Over!\n"); printf("\n"); break; //break instead of return _0_ because I'm using a void main, and want to exit my game not the whole program. } else if(userchoice != 1 && userchoice != 2 && choice != 99) { printf("Invalid input! Please enter 1 or 2 only.\n"); } } while(userchoice !=1 && userchoice != 2 && choice != 99); if(choice == 99) break; /*if choice wasn't _2_, they are still in the game*/ if(choice != 2) { do{/*get valid input from user for decision _4_ and take action based on decision. */ printf("\n");//separator printf("The grandpa troll tells you a story the enemies of the island of them are the pirates and other are cyclops. The next day you help trolls to catch fishes on the sea. However, you see a pirate ship on the other side of the island. What do you do?\n"); printf("1: You try to befriend them and use the opportunity to get away from the island.\n"); printf("2: You hide and run to tell the trolls about the arriving pirates on the island...\n"); printf("\n");//separator printf("Your choice: "); scanf(" %d", &userchoice); choice = userchoice; //to set choice to userchoice to see if _99_ was read in to exit. if(userchoice==1) { printf("\n");//separator printf("You are surrounded by pirates, and make you their slave. You are taken away from the island but stuck with pirates forever.\n"); printf("\n"); printf("Game Over!\n"); printf("\n"); break; //break instead of return _0_ because I'm using my void main and want to exit to my game only. } else if(userchoice == 2) { printf("\n"); printf("The trolls are happy you told them about the pirates are exploring the beach. The trolls create an invisible barrier to keep you and other trolls safe away from the pirates.\n"); } else if(userchoice != 1 && userchoice != 2 && choice != 99) { printf("Invalid input! Please enter 1 or 2 only.\n"); } } while(userchoice != 1 && userchoice !=2 && choice != 99); if(choice == 99) break; if(choice != 1) { do{ /*get valid input from user for decision _5_ and take action based on decision.*/ printf("\n"); printf("The pirates did not find any interesting on the island, they leave. Trolls and you gather and celebrate. However, the celebration is too loud, the cyclops came, break the barrier, and attacked the trolls home. The grandfather troll try to combat the cyclops but failed. He hand you down his magical pendant What do you do?\n"); printf("1: Take the magical pendant to fix your broken flying broom stick, save your self and ran away.\n"); printf("2: Take the pendant, fix your magical wand, summon fairies alliances to save trolls including the grandfather from evil cyclops.\n"); printf("\n");//separator printf("Your choice: "); scanf(" %d", &userchoice); choice = userchoice;//to set choice to userchoice to see if _ 99_ was read in to exit. if(userchoice==1) { printf("\n");//separator printf("Because of your selfishness, your flying broomstick broke, you trip over a cliff pluging to inevitable death.\n"); printf("\n"); printf("Game Over!\n"); printf("\n"); break;//break instead of return _0_ because I'm using a void main and only want to exit my game. } else if(userchoice==2) { printf("\n");//separator printf("The grandfather troll let you keep his magical pendant as a present, teach you to summon door a shorcut passage way going to your family home. Everyone surprise to welcome you warmly to celebrate Christmass holiday with them.\n "); printf("\n"); printf("You win the game. The End!\n"); printf("\n");//separator } else if(userchoice != 1 && userchoice != 2 && choice != 99) { printf("Invalid input! Please enter 1 or 2 only.\n"); } } while(userchoice !=1 && userchoice !=2 && choice !=99); if(choice == 99) break; } } } } } break; } case 35: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 36: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } case 37: { while(choice != 99) { puts("you open the door and find ........"); scanf("%d",&choice); } break; } } } } void extraCredit(void) { printf("%s", "You have gained extra credit!\nIf you beat me in a duel!\n"); printf("%s", "DUEL MECHANICS WILL BE IMPLEMENTED IN THE NEXT UPDATE\n\n"); } void ignoreExtra(void) { int counter = 0; printf("%s", "Take the extra credit, I'm not gonna ask you again!\n"); int choice; printf("%s", "Please type 1 for extra credit\n or you will be kicked out of room THREE!\n"); scanf("%d", &choice); switch(choice) { case 1: extraCredit(); break; defualt: printf("%s", "You have been kicked!...LEAVE THIS ROOM AT ONCE!\n"); break; } } int choice1(int number) { int answer = 0; int guess = 0; printf(" %d + (%d^2) - (%d) = ?", number, 8, 6); scanf(" %d", &guess); answer = (number + (pow(8, 2)) - 6); if(answer == guess) { puts("\nYou have guessed the anwer correctly. You may get the map to get out of the mansion...Good Job!\n"); return EXIT_SUCCESS; } else { printf("\nThe answer was %d. You guessed it wrong. You have failed...\n", answer); return EXIT_SUCCESS; } } int choice2(char *ptr) { int size = 40, i, length = 0; char copy[size]; char guess[size]; strcpy(copy, ptr); puts("Please enter your guess(one chance):"); scanf(" %s", guess); length = strlen(guess); for(i = 0; i < length;i++) { if(isupper(guess[i])) { guess[i] = tolower(guess[i]); } } if(!strcmp(copy, guess)) { puts("Guessed correctly!\n"); } else { puts("Guess was incorrect!\n"); } return EXIT_SUCCESS; } int choice3(int number1) { int answer = 0; printf("magic number is : %d\n", number1); printf("10 + magic number = %d\n", (10 + number1)); printf("5 * magic number = %d\n", (5 * number1)); printf("20 - magic number = %d\n", (20 - number1)); printf("What is your guess? "); scanf(" %d", &answer); if(answer == number1) { puts("You guessed it correctly!"); return EXIT_SUCCESS; } else { puts("You guessed it wrong!"); return EXIT_SUCCESS; } } void gameRules() //simple function that prints rules of game to user... { puts("\nThe rules of this card game - craps - are simple..."); puts("If you roll a 7 or 11 immediately...you win!"); puts("If you roll a 2, 3, or 12 immediately...you lose!"); puts("If you roll anything besides those numbers, you want to roll that number again before you roll a 7 to win!\n"); } void gameCraps() //function play craps that does the logic for the game... { int randomint(int x, int y); //function to call random integer... srand(time(NULL)); //random seed set to clock time int die1, die2, die3, die4, rollcount, rollcount2; //4 die and 2 roll ints die1 = randomint(1,6); //setting first die to equal random int from 1-6 die2 = randomint(1,6); //same as above with second die rollcount = die1 + die2; //roll function equals die 1 and die 2.... printf("You rolled a %i\n",rollcount); //print statement letting user know their roll if(rollcount == 7 || rollcount == 11)//if roll is equal to 7 or 11...player wins game { printf("You Win!\n"); //let user know they won game printf("Enter 'y' or 'Y' to roll again. Enter '99' to exit program.\n"); return; } else if(rollcount == 2 || rollcount == 3 || rollcount == 12) //if roll is equal to a 2, 3, or 12....player loses game { printf("You Lose :(\n"); //let user know they lost game printf("Enter 'y' or 'Y' to roll again. Enter '99' to exit program.\n"); return; } else // otherwise on every other number roll... { do //run this command at least once...while conditions above aren't met... { die3 = randomint(1,6); //similar to above, set die3 to equal a random int between 1-6 die4 = randomint(1,6); //same as above w/4th die rollcount2 = die3 + die4; //our 2nd roll equals die 3 + die 4 printf("You rolled a %d\n", rollcount2); //let user know what they rolled w/2nd roll... if(rollcount == rollcount2) //if our 2nd roll is equal to our first roll... { printf("You Win\n"); //let user know they won game printf("Enter 'y' or 'Y' twice to roll again. Enter '99' to exit program.\n"); return; } } while(rollcount != 7); //while our 2nd roll is not equal to 7... printf("You Lose :(\n"); //let user know they lost game... printf("Enter 'y' or 'Y' twice to roll again. Enter '99' to exit program.\n"); } } int randomint(int x, int y) //random integer function to work craps game { return rand()%(y - x + 1); //ensures random number is generated }
the_stack_data/395804.c
/* * Copyright (c) 2000, 2001, 2002, 2003, 2004, 2005, 2008, 2009 * The President and Fellows of Harvard College. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE UNIVERSITY 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 UNIVERSITY 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. */ /* * farm.c * * Run a bunch of cpu pigs and one cat. * The file it cats is "catfile". This should be created in advance. * * This test should itself run correctly when the basic system calls * are complete. It may be helpful for scheduler performance analysis. */ #include <unistd.h> #include <err.h> static char *hargv[2] = { (char *)"hog", NULL }; static char *cargv[3] = { (char *)"cat", (char *)"catfile", NULL }; #define MAXPROCS 6 static int pids[MAXPROCS], npids; static void spawnv(const char *prog, char **argv) { int pid = fork(); switch (pid) { case -1: err(1, "fork"); case 0: /* child */ execv(prog, argv); err(1, "%s", prog); default: /* parent */ pids[npids++] = pid; break; } } static void waitall(void) { int i, status; for (i=0; i<npids; i++) { if (waitpid(pids[i], &status, 0)<0) { warn("waitpid for %d", pids[i]); } else if (WIFSIGNALED(status)) { warnx("pid %d: signal %d", pids[i], WTERMSIG(status)); } else if (WEXITSTATUS(status) != 0) { warnx("pid %d: exit %d", pids[i], WEXITSTATUS(status)); } } } static void hog(void) { spawnv("/testbin/hog", hargv); } static void cat(void) { spawnv("/bin/cat", cargv); } int main() { hog(); hog(); hog(); cat(); waitall(); return 0; }
the_stack_data/15763545.c
/* Copyright (C) 2005, 2008 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #include <errno.h> #include <unistd.h> int __getgroups_chk (int size, __gid_t list[], size_t listlen) { if (__builtin_expect (size < 0, 0)) { __set_errno (EINVAL); return -1; } if (__builtin_expect (size * sizeof (__gid_t) > listlen, 0)) __chk_fail (); return __getgroups (size, list); }
the_stack_data/143796.c
/*Exercise 2 - Selection Write a program to calculate the amount to be paid for a rented vehicle. • Input the distance the van has travelled • The first 30 km is at a rate of 50/= per km. • The remaining distance is calculated at the rate of 40/= per km. e.g. Distance -> 20 Amount = 20 x 50 = 1000 Distance -> 50 Amount = 30 x 50 + (50-30) x 40 = 2300*/ #include <stdio.h> int main() { int distance; //define variables float amount; printf("\nEnter the distance :"); //Ask user to enter the distance scanf("%d" ,&distance); if(distance < 30 ) //condition { amount = (float)distance * 50; } else { amount = (float)30 * 50 + (distance - 30) * 40; } printf("\nAmount : %.2f" , amount); //print amount return 0; }
the_stack_data/151706822.c
/* ******************************************************************************* * Copyright (c) 2020-2021, STMicroelectronics * All rights reserved. * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ******************************************************************************* */ #if defined(ARDUINO_GENERIC_F051K6TX) || defined(ARDUINO_GENERIC_F051K8TX) #include "pins_arduino.h" /** * @brief System Clock Configuration * @param None * @retval None */ WEAK void SystemClock_Config(void) { /* SystemClock_Config can be generated by STM32CubeMX */ #warning "SystemClock_Config() is empty. Default clock at reset is used." } #endif /* ARDUINO_GENERIC_* */
the_stack_data/225143328.c
#include<stdio.h> long factorial( long n){ if(n==0){ return 1; } // if number is negetive, invalid input if(n<0){ return -1; } return n*factorial(n-1); } int main(){ long a; long fact; // read the input scanf("%ld",&a); // find the factorial of the input fact=factorial(a); printf( "%ld", factorial(a) ); return 0; }
the_stack_data/184596.c
#include <stdio.h> #include <stdlib.h> int main(void) { int *list= malloc(3 * sizeof(int)); if (list == NULL) { return 1; } list[0] = 1; list[1] = 2; list[2] = 3; int *tmp = realloc(list, 4 * sizeof(int)); if (tmp == NULL) { return 1; } list = tmp; list[3] = 4; for (int i = 0; i < 4; i++) { printf("%i\n",list[i]); } free(list); }
the_stack_data/23865.c
#include <stdio.h> #include <time.h> int main(int argc, char **argv) { time_t timeBase; struct tm *timeInfo; time(&timeBase); timeInfo = localtime(&timeBase); printf("Current time: %s", asctime(timeInfo)); return 0; }
the_stack_data/115764411.c
/******************************************************************************* * * Este programa faz parte do curso sobre tempo real do Laboratorio Embry-Riddle * * Seguem os comentarios originais: * * Experiment #5: Semaphores * * Programmer: Eric Sorton * Date: 3/17/97 * For: MSE599, Special Topics Class * * Purpose: The purpose of this program is to demonstrate how semaphores * can be used to protect a critical region. Its sole purpose * is to print a character string (namely the alphabet) to the * screen. Any number of processes can be used to cooperatively * (or non-cooperatively) print the string to the screen. An * index is stored in shared memory, this index is the index into * the array that identifies which character within the string * should be printed next. Without semaphores, all the processes * access this index simultaneously and conflicts occur. With * semahpores, the character string is displayed neatly to the * screen. * * The optional semaphore protection can be compiled into the * program using the MACRO definition of PROTECT. To compile * the semaphore protection into the program, uncomment the * #define below. * * * Proposito: O proposito deste programa e o de demonstrar como semaforos * podem ser usados para proteger uma regiao critica. O programa exibe * um string de caracteres (na realidade um alfabeto). Um número * qualquer de processos pode ser usado para exibir o string, seja * de maneira cooperativa ou nao cooperativa. Um indice e armazenado * em memoria compartilhada, este indice e aquele usado para * identificar qual caractere deve ser exibido em seguida. Sem * semaforos, todos os processos acessam esse indice concorrentemente * causando conflitos. Com semaforos, o string de caracteres e exibido * de maneira correta (caracteres do alfabeto na ordem correta e apenas * um de cada caractere). * * A protecao opcional com semaforo pode ser compilada no programa * usando a definicao de MACRO denominada PROTECT. Para compilar a * protecao com semaforo, retire o comentario do #define que segue. * * *******************************************************************************/ #define PROTECT /* * Includes Necessarios */ #include <errno.h> /* errno and error codes */ #include <sys/time.h> /* for gettimeofday() */ #include <stdio.h> /* for printf() */ #include <unistd.h> /* for fork() */ #include <sys/types.h> /* for wait() */ #include <sys/wait.h> /* for wait() */ #include <signal.h> /* for kill(), sigsuspend(), others */ #include <sys/ipc.h> /* for all IPC function calls */ #include <sys/shm.h> /* for shmget(), shmat(), shmctl() */ #include <sys/sem.h> /* for semget(), semop(), semctl() */ #include <stdlib.h> /* * Constantes Necessarias */ #define SEM_KEY 0x1243 #define SHM_KEY 0x1432 #define NO_OF_CHILDREN 3 /* * As seguintes variaveis globais contem informacao importante. A variavel * g_sem_id e g_shm_id contem as identificacoes IPC para o semaforo e para * o segmento de memoria compartilhada que sao usados pelo programa. A variavel * g_shm_addr e um ponteiro inteiro que aponta para o segmento de memoria * compartilhada que contera o indice inteiro da matriz de caracteres que contem * o alfabeto que sera exibido. */ int g_sem_id; int g_shm_id; int *g_shm_addr; /*Arquivo para salvarmos o resultado*/ FILE *arq; /* * As seguintes duas estruturas contem a informacao necessaria para controlar * semaforos em relacao a "fecharem", se nao permitem acesso, ou * "abrirem", se permitirem acesso. As estruturas sao incializadas ao inicio * do programa principal e usadas na rotina PrintAlphabet(). Como elas sao * inicializadas no programa principal, antes da criacao dos processos filhos, * elas podem ser usadas nesses processos sem a necessidade de nova associacao * ou mudancas. */ struct sembuf g_sem_op1[1]; struct sembuf g_sem_op2[1]; /* * O seguinte vetor de caracteres contem o alfabeto que constituira o string * que sera exibido. */ char g_letters_and_numbers[] = " ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz 1234567890"; /* * Funcoes */ void PrintChars( void ); /* * Programa Principal */ int main( int argc, char *argv[] ) { /* * Variaveis necessarias */ pid_t rtn; int count; /* * Para armazenar os ids dos processos filhos, permitindo o posterior * uso do comando kill */ int pid[NO_OF_CHILDREN]; /* * Construindo a estrutura de controle do semaforo */ g_sem_op1[0].sem_num = 0; g_sem_op1[0].sem_op = -1; //Bloquear g_sem_op1[0].sem_flg = 0; /* * Pergunta 1: Se usada a estrutura g_sem_op1 terá qual efeito em um conjunto de semáforos? */ g_sem_op2[0].sem_num = 0; g_sem_op2[0].sem_op = 1; //Desbloquear g_sem_op2[0].sem_flg = 0; /* * Criando o semaforo */ if( ( g_sem_id = semget( SEM_KEY, 1, IPC_CREAT | 0666 ) ) == -1 ) { fprintf(stderr,"chamada a semget() falhou, impossivel criar o conjunto de semaforos!"); exit(1); } if( semop( g_sem_id, g_sem_op2, 1 ) == -1 ) { fprintf(stderr,"chamada semop() falhou, impossivel inicializar o semaforo!"); exit(1); } /* * Pergunta 2: Para que serve esta operacao semop(), se não está na saída de uma região crítica? */ /* * Criando o segmento de memoria compartilhada */ if( (g_shm_id = shmget( SHM_KEY, sizeof(int), IPC_CREAT | 0666)) == -1 ) { fprintf(stderr,"Impossivel criar o segmento de memoria compartilhada!\n"); exit(1); } if( (g_shm_addr = (int *)shmat(g_shm_id, NULL, 0)) == (int *)-1 ) { fprintf(stderr,"Impossivel associar o segmento de memoria compartilhada!\n"); exit(1); } *g_shm_addr = 0; /* * Pergunta 3: Para que serve essa inicialização da memória compartilhada com zero? */ /* * Criando os filhos */ rtn = 1; for( count = 0; count < NO_OF_CHILDREN; count++ ) { if( rtn != 0 ) { pid[count] = rtn = fork(); } else { break; } } /* * Verificando o valor retornado para determinar se o processo e * pai ou filho */ if( rtn == 0 ) { /* * Eu sou um filho */ //printf("Filho %i comecou ...\n", count); PrintChars(); } else { usleep(15000); /* * Matando os filhos */ int child; for(child = 0; child < NO_OF_CHILDREN; child++){ kill(pid[child], SIGKILL); } /* * Removendo a memoria compartilhada */ if( shmctl(g_shm_id,IPC_RMID,NULL) != 0 ) { fprintf(stderr,"Impossivel remover o segmento de memoria compartilhada!\n"); exit(1); } /* * Removendo o semaforo */ if( semctl( g_sem_id, 0, IPC_RMID, 0) != 0 ) { fprintf(stderr,"Impossivel remover o conjunto de semaforos!\n"); exit(1); } fprintf(stderr, "\n"); exit(0); } } /* * Pergunta 4: se os filhos ainda não terminaram, semctl e shmctl, com o parametro IPC-RMID, nao * permitem mais o acesso ao semáforo / memória compartilhada? */ /* * Esta rotina realiza a exibicao de caracteres. Nela e calculado um numero * pseudo-randomico entre 1 e 3 para determinar o numero de caracteres a exibir. * Se a protecao esta estabelecida, a rotina entao consegue o recurso. Em * seguida, PrintChars() acessa o indice com seu valor corrente a partir da * memoria compartilhada. A rotina entra em loop, exibindo o numero aleatorio de * caracteres. Finalmente, a rotina incrementa o indice, conforme o necessario, * e libera o recurso, se for o caso. */ void PrintChars( void ) { struct timeval tv; int number; int tmp_index; int i; /* * Este tempo permite que todos os filhos sejam inciados */ usleep(200); /* * Entrando no loop principal */ while(1) { /* * Conseguindo o tempo corrente, os microsegundos desse tempo * sao usados como um numero pseudo-randomico. Em seguida, * calcula o numero randomico atraves de um algoritmo simples */ if( gettimeofday( &tv, NULL ) == -1 ) { fprintf(stderr,"Impossivel conseguir o tempo atual, terminando.\n"); exit(1); } number = ((tv.tv_usec / 47) % 3) + 1; //tv_usec = pega em microsegundos o tempo //printf("valor number: %c \n\n\n", number); /* * Pergunta 5: quais os valores possíveis de serem atribuidos * a number? */ /* * O #ifdef PROTECT inclui este pedaco de codigo se a macro * PROTECT estiver definida. Para sua definicao, retire o comentario * que a acompanha. semop() e chamada para fechar o semaforo. */ #ifdef PROTECT if( semop( g_sem_id, g_sem_op1, 1 ) == -1 ) { fprintf(stderr,"chamada semop() falhou, impossivel fechar o recurso!"); exit(1); } #endif /* * Lendo o indice do segmento de memoria compartilhada */ tmp_index = *g_shm_addr; if( (arq = fopen("resultados.txt", "a+")) == NULL){ printf("Erro na abertura do arquivo"); exit(1); } /* * Repita o numero especificado de vezes, esteja certo de nao * ultrapassar os limites do vetor, o comando if garante isso */ for( i = 0; i < number; i++ ) { if( ! (tmp_index + i > sizeof(g_letters_and_numbers)) ) { fprintf(stderr,"%c", g_letters_and_numbers[tmp_index + i]); fputc(g_letters_and_numbers[tmp_index + i], arq); usleep(1); } } /* * Atualizando o indice na memoria compartilhada */ *g_shm_addr = tmp_index + i; /* * Se o indice e maior que o tamanho do alfabeto, exibe um * caractere return para iniciar a linha seguinte e coloca * zero no indice */ if( tmp_index + i > sizeof(g_letters_and_numbers) ) { fprintf(stderr, "\n"); *g_shm_addr = 0; } /* * Liberando o recurso se a macro PROTECT estiver definida */ #ifdef PROTECT if( semop( g_sem_id, g_sem_op2, 1 ) == -1 ) { fprintf(stderr,"chamada semop() falhou, impossivel liberar o recurso!"); exit(1); } #endif fclose(arq); } }
the_stack_data/104827538.c
#include <stdio.h> #include <stdlib.h> #include <locale.h> int main() { setlocale(LC_ALL, "Portuguese"); int m[4][4], i, j, maior, pi, pj; printf ("\nForneça os valores da matriz:\n\n"); for ( i=0; i<4; i++ ){ for ( j=0; j<4; j++ ) { printf ("\nLinha %d / Coluna %d = ", i+1, j+1); scanf ("%d", &m[ i ][ j ]); } } printf("\nMatriz:\n"); for ( i=0; i<4; i++ ){ for ( j=0; j<4; j++ ) { printf ("[%d] ", m[i][j]); } printf("\n"); } for(i=0;i<4;i++){ for(j=0;j<4;j++){ if(j==0 && i==0){ maior=m[i][j]; pi=i; pj=j;} if(maior < m[i][j]){ maior=m[i][j]; pi=i; pj=j;} }} printf("\nLocalização do maior valor: Linha %d, coluna %d\n", pi+1, pj+1); return 0; }
the_stack_data/83031.c
#include <stdio.h> main() { int i; i = 0; sleep(10); while (i < 5) { system("date"); sleep(5); i++; } while (1) { system("date"); sleep(10); } }
the_stack_data/115765799.c
char *ft_strncpy(char *dest, char *src, unsigned int n) { unsigned int i; i = 0; while (src[i] != '\0' && i < n) { dest[i] = src[i]; i++; } while (i < n) { dest[i] = '\0'; i++; } return (dest); }
the_stack_data/50137659.c
// WARNING in osif_probe/usb_submit_urb // https://syzkaller.appspot.com/bug?id=9d7dadd15b8819d73f41 // status:0 // autogenerated by syzkaller (https://github.com/google/syzkaller) #define _GNU_SOURCE #include <dirent.h> #include <endian.h> #include <errno.h> #include <fcntl.h> #include <signal.h> #include <stdarg.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/mount.h> #include <sys/prctl.h> #include <sys/stat.h> #include <sys/syscall.h> #include <sys/types.h> #include <sys/wait.h> #include <time.h> #include <unistd.h> #include <linux/usb/ch9.h> static unsigned long long procid; static void sleep_ms(uint64_t ms) { usleep(ms * 1000); } static uint64_t current_time_ms(void) { struct timespec ts; if (clock_gettime(CLOCK_MONOTONIC, &ts)) exit(1); return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000; } static bool write_file(const char* file, const char* what, ...) { char buf[1024]; va_list args; va_start(args, what); vsnprintf(buf, sizeof(buf), what, args); va_end(args); buf[sizeof(buf) - 1] = 0; int len = strlen(buf); int fd = open(file, O_WRONLY | O_CLOEXEC); if (fd == -1) return false; if (write(fd, buf, len) != len) { int err = errno; close(fd); errno = err; return false; } close(fd); return true; } #define MAX_FDS 30 #define USB_MAX_IFACE_NUM 4 #define USB_MAX_EP_NUM 32 #define USB_MAX_FDS 6 struct usb_endpoint_index { struct usb_endpoint_descriptor desc; int handle; }; struct usb_iface_index { struct usb_interface_descriptor* iface; uint8_t bInterfaceNumber; uint8_t bAlternateSetting; uint8_t bInterfaceClass; struct usb_endpoint_index eps[USB_MAX_EP_NUM]; int eps_num; }; struct usb_device_index { struct usb_device_descriptor* dev; struct usb_config_descriptor* config; uint8_t bDeviceClass; uint8_t bMaxPower; int config_length; struct usb_iface_index ifaces[USB_MAX_IFACE_NUM]; int ifaces_num; int iface_cur; }; struct usb_info { int fd; struct usb_device_index index; }; static struct usb_info usb_devices[USB_MAX_FDS]; static int usb_devices_num; static bool parse_usb_descriptor(const char* buffer, size_t length, struct usb_device_index* index) { if (length < sizeof(*index->dev) + sizeof(*index->config)) return false; memset(index, 0, sizeof(*index)); index->dev = (struct usb_device_descriptor*)buffer; index->config = (struct usb_config_descriptor*)(buffer + sizeof(*index->dev)); index->bDeviceClass = index->dev->bDeviceClass; index->bMaxPower = index->config->bMaxPower; index->config_length = length - sizeof(*index->dev); index->iface_cur = -1; size_t offset = 0; while (true) { if (offset + 1 >= length) break; uint8_t desc_length = buffer[offset]; uint8_t desc_type = buffer[offset + 1]; if (desc_length <= 2) break; if (offset + desc_length > length) break; if (desc_type == USB_DT_INTERFACE && index->ifaces_num < USB_MAX_IFACE_NUM) { struct usb_interface_descriptor* iface = (struct usb_interface_descriptor*)(buffer + offset); index->ifaces[index->ifaces_num].iface = iface; index->ifaces[index->ifaces_num].bInterfaceNumber = iface->bInterfaceNumber; index->ifaces[index->ifaces_num].bAlternateSetting = iface->bAlternateSetting; index->ifaces[index->ifaces_num].bInterfaceClass = iface->bInterfaceClass; index->ifaces_num++; } if (desc_type == USB_DT_ENDPOINT && index->ifaces_num > 0) { struct usb_iface_index* iface = &index->ifaces[index->ifaces_num - 1]; if (iface->eps_num < USB_MAX_EP_NUM) { memcpy(&iface->eps[iface->eps_num].desc, buffer + offset, sizeof(iface->eps[iface->eps_num].desc)); iface->eps_num++; } } offset += desc_length; } return true; } static struct usb_device_index* add_usb_index(int fd, const char* dev, size_t dev_len) { int i = __atomic_fetch_add(&usb_devices_num, 1, __ATOMIC_RELAXED); if (i >= USB_MAX_FDS) return NULL; if (!parse_usb_descriptor(dev, dev_len, &usb_devices[i].index)) return NULL; __atomic_store_n(&usb_devices[i].fd, fd, __ATOMIC_RELEASE); return &usb_devices[i].index; } static struct usb_device_index* lookup_usb_index(int fd) { for (int i = 0; i < USB_MAX_FDS; i++) { if (__atomic_load_n(&usb_devices[i].fd, __ATOMIC_ACQUIRE) == fd) { return &usb_devices[i].index; } } return NULL; } struct vusb_connect_string_descriptor { uint32_t len; char* str; } __attribute__((packed)); struct vusb_connect_descriptors { uint32_t qual_len; char* qual; uint32_t bos_len; char* bos; uint32_t strs_len; struct vusb_connect_string_descriptor strs[0]; } __attribute__((packed)); static const char default_string[] = {8, USB_DT_STRING, 's', 0, 'y', 0, 'z', 0}; static const char default_lang_id[] = {4, USB_DT_STRING, 0x09, 0x04}; static bool lookup_connect_response_in(int fd, const struct vusb_connect_descriptors* descs, const struct usb_ctrlrequest* ctrl, char** response_data, uint32_t* response_length) { struct usb_device_index* index = lookup_usb_index(fd); uint8_t str_idx; if (!index) return false; switch (ctrl->bRequestType & USB_TYPE_MASK) { case USB_TYPE_STANDARD: switch (ctrl->bRequest) { case USB_REQ_GET_DESCRIPTOR: switch (ctrl->wValue >> 8) { case USB_DT_DEVICE: *response_data = (char*)index->dev; *response_length = sizeof(*index->dev); return true; case USB_DT_CONFIG: *response_data = (char*)index->config; *response_length = index->config_length; return true; case USB_DT_STRING: str_idx = (uint8_t)ctrl->wValue; if (descs && str_idx < descs->strs_len) { *response_data = descs->strs[str_idx].str; *response_length = descs->strs[str_idx].len; return true; } if (str_idx == 0) { *response_data = (char*)&default_lang_id[0]; *response_length = default_lang_id[0]; return true; } *response_data = (char*)&default_string[0]; *response_length = default_string[0]; return true; case USB_DT_BOS: *response_data = descs->bos; *response_length = descs->bos_len; return true; case USB_DT_DEVICE_QUALIFIER: if (!descs->qual) { struct usb_qualifier_descriptor* qual = (struct usb_qualifier_descriptor*)response_data; qual->bLength = sizeof(*qual); qual->bDescriptorType = USB_DT_DEVICE_QUALIFIER; qual->bcdUSB = index->dev->bcdUSB; qual->bDeviceClass = index->dev->bDeviceClass; qual->bDeviceSubClass = index->dev->bDeviceSubClass; qual->bDeviceProtocol = index->dev->bDeviceProtocol; qual->bMaxPacketSize0 = index->dev->bMaxPacketSize0; qual->bNumConfigurations = index->dev->bNumConfigurations; qual->bRESERVED = 0; *response_length = sizeof(*qual); return true; } *response_data = descs->qual; *response_length = descs->qual_len; return true; default: break; } break; default: break; } break; default: break; } return false; } typedef bool (*lookup_connect_out_response_t)( int fd, const struct vusb_connect_descriptors* descs, const struct usb_ctrlrequest* ctrl, bool* done); static bool lookup_connect_response_out_generic( int fd, const struct vusb_connect_descriptors* descs, const struct usb_ctrlrequest* ctrl, bool* done) { switch (ctrl->bRequestType & USB_TYPE_MASK) { case USB_TYPE_STANDARD: switch (ctrl->bRequest) { case USB_REQ_SET_CONFIGURATION: *done = true; return true; default: break; } break; } return false; } #define UDC_NAME_LENGTH_MAX 128 struct usb_raw_init { __u8 driver_name[UDC_NAME_LENGTH_MAX]; __u8 device_name[UDC_NAME_LENGTH_MAX]; __u8 speed; }; enum usb_raw_event_type { USB_RAW_EVENT_INVALID = 0, USB_RAW_EVENT_CONNECT = 1, USB_RAW_EVENT_CONTROL = 2, }; struct usb_raw_event { __u32 type; __u32 length; __u8 data[0]; }; struct usb_raw_ep_io { __u16 ep; __u16 flags; __u32 length; __u8 data[0]; }; #define USB_RAW_EPS_NUM_MAX 30 #define USB_RAW_EP_NAME_MAX 16 #define USB_RAW_EP_ADDR_ANY 0xff struct usb_raw_ep_caps { __u32 type_control : 1; __u32 type_iso : 1; __u32 type_bulk : 1; __u32 type_int : 1; __u32 dir_in : 1; __u32 dir_out : 1; }; struct usb_raw_ep_limits { __u16 maxpacket_limit; __u16 max_streams; __u32 reserved; }; struct usb_raw_ep_info { __u8 name[USB_RAW_EP_NAME_MAX]; __u32 addr; struct usb_raw_ep_caps caps; struct usb_raw_ep_limits limits; }; struct usb_raw_eps_info { struct usb_raw_ep_info eps[USB_RAW_EPS_NUM_MAX]; }; #define USB_RAW_IOCTL_INIT _IOW('U', 0, struct usb_raw_init) #define USB_RAW_IOCTL_RUN _IO('U', 1) #define USB_RAW_IOCTL_EVENT_FETCH _IOR('U', 2, struct usb_raw_event) #define USB_RAW_IOCTL_EP0_WRITE _IOW('U', 3, struct usb_raw_ep_io) #define USB_RAW_IOCTL_EP0_READ _IOWR('U', 4, struct usb_raw_ep_io) #define USB_RAW_IOCTL_EP_ENABLE _IOW('U', 5, struct usb_endpoint_descriptor) #define USB_RAW_IOCTL_EP_DISABLE _IOW('U', 6, __u32) #define USB_RAW_IOCTL_EP_WRITE _IOW('U', 7, struct usb_raw_ep_io) #define USB_RAW_IOCTL_EP_READ _IOWR('U', 8, struct usb_raw_ep_io) #define USB_RAW_IOCTL_CONFIGURE _IO('U', 9) #define USB_RAW_IOCTL_VBUS_DRAW _IOW('U', 10, __u32) #define USB_RAW_IOCTL_EPS_INFO _IOR('U', 11, struct usb_raw_eps_info) #define USB_RAW_IOCTL_EP0_STALL _IO('U', 12) #define USB_RAW_IOCTL_EP_SET_HALT _IOW('U', 13, __u32) #define USB_RAW_IOCTL_EP_CLEAR_HALT _IOW('U', 14, __u32) #define USB_RAW_IOCTL_EP_SET_WEDGE _IOW('U', 15, __u32) static int usb_raw_open() { return open("/dev/raw-gadget", O_RDWR); } static int usb_raw_init(int fd, uint32_t speed, const char* driver, const char* device) { struct usb_raw_init arg; strncpy((char*)&arg.driver_name[0], driver, sizeof(arg.driver_name)); strncpy((char*)&arg.device_name[0], device, sizeof(arg.device_name)); arg.speed = speed; return ioctl(fd, USB_RAW_IOCTL_INIT, &arg); } static int usb_raw_run(int fd) { return ioctl(fd, USB_RAW_IOCTL_RUN, 0); } static int usb_raw_event_fetch(int fd, struct usb_raw_event* event) { return ioctl(fd, USB_RAW_IOCTL_EVENT_FETCH, event); } static int usb_raw_ep0_write(int fd, struct usb_raw_ep_io* io) { return ioctl(fd, USB_RAW_IOCTL_EP0_WRITE, io); } static int usb_raw_ep0_read(int fd, struct usb_raw_ep_io* io) { return ioctl(fd, USB_RAW_IOCTL_EP0_READ, io); } static int usb_raw_ep_enable(int fd, struct usb_endpoint_descriptor* desc) { return ioctl(fd, USB_RAW_IOCTL_EP_ENABLE, desc); } static int usb_raw_ep_disable(int fd, int ep) { return ioctl(fd, USB_RAW_IOCTL_EP_DISABLE, ep); } static int usb_raw_configure(int fd) { return ioctl(fd, USB_RAW_IOCTL_CONFIGURE, 0); } static int usb_raw_vbus_draw(int fd, uint32_t power) { return ioctl(fd, USB_RAW_IOCTL_VBUS_DRAW, power); } static int usb_raw_ep0_stall(int fd) { return ioctl(fd, USB_RAW_IOCTL_EP0_STALL, 0); } static void set_interface(int fd, int n) { struct usb_device_index* index = lookup_usb_index(fd); if (!index) return; if (index->iface_cur >= 0 && index->iface_cur < index->ifaces_num) { for (int ep = 0; ep < index->ifaces[index->iface_cur].eps_num; ep++) { int rv = usb_raw_ep_disable( fd, index->ifaces[index->iface_cur].eps[ep].handle); if (rv < 0) { } else { } } } if (n >= 0 && n < index->ifaces_num) { for (int ep = 0; ep < index->ifaces[n].eps_num; ep++) { int rv = usb_raw_ep_enable(fd, &index->ifaces[n].eps[ep].desc); if (rv < 0) { } else { index->ifaces[n].eps[ep].handle = rv; } } index->iface_cur = n; } } static int configure_device(int fd) { struct usb_device_index* index = lookup_usb_index(fd); if (!index) return -1; int rv = usb_raw_vbus_draw(fd, index->bMaxPower); if (rv < 0) { return rv; } rv = usb_raw_configure(fd); if (rv < 0) { return rv; } set_interface(fd, 0); return 0; } #define USB_MAX_PACKET_SIZE 4096 struct usb_raw_control_event { struct usb_raw_event inner; struct usb_ctrlrequest ctrl; char data[USB_MAX_PACKET_SIZE]; }; struct usb_raw_ep_io_data { struct usb_raw_ep_io inner; char data[USB_MAX_PACKET_SIZE]; }; static volatile long syz_usb_connect_impl(uint64_t speed, uint64_t dev_len, const char* dev, const struct vusb_connect_descriptors* descs, lookup_connect_out_response_t lookup_connect_response_out) { if (!dev) { return -1; } int fd = usb_raw_open(); if (fd < 0) { return fd; } if (fd >= MAX_FDS) { close(fd); return -1; } struct usb_device_index* index = add_usb_index(fd, dev, dev_len); if (!index) { return -1; } char device[32]; sprintf(&device[0], "dummy_udc.%llu", procid); int rv = usb_raw_init(fd, speed, "dummy_udc", &device[0]); if (rv < 0) { return rv; } rv = usb_raw_run(fd); if (rv < 0) { return rv; } bool done = false; while (!done) { struct usb_raw_control_event event; event.inner.type = 0; event.inner.length = sizeof(event.ctrl); rv = usb_raw_event_fetch(fd, (struct usb_raw_event*)&event); if (rv < 0) { return rv; } if (event.inner.type != USB_RAW_EVENT_CONTROL) continue; char* response_data = NULL; uint32_t response_length = 0; if (event.ctrl.bRequestType & USB_DIR_IN) { if (!lookup_connect_response_in(fd, descs, &event.ctrl, &response_data, &response_length)) { usb_raw_ep0_stall(fd); continue; } } else { if (!lookup_connect_response_out(fd, descs, &event.ctrl, &done)) { usb_raw_ep0_stall(fd); continue; } response_data = NULL; response_length = event.ctrl.wLength; } if ((event.ctrl.bRequestType & USB_TYPE_MASK) == USB_TYPE_STANDARD && event.ctrl.bRequest == USB_REQ_SET_CONFIGURATION) { rv = configure_device(fd); if (rv < 0) { return rv; } } struct usb_raw_ep_io_data response; response.inner.ep = 0; response.inner.flags = 0; if (response_length > sizeof(response.data)) response_length = 0; if (event.ctrl.wLength < response_length) response_length = event.ctrl.wLength; response.inner.length = response_length; if (response_data) memcpy(&response.data[0], response_data, response_length); else memset(&response.data[0], 0, response_length); if (event.ctrl.bRequestType & USB_DIR_IN) { rv = usb_raw_ep0_write(fd, (struct usb_raw_ep_io*)&response); } else { rv = usb_raw_ep0_read(fd, (struct usb_raw_ep_io*)&response); } if (rv < 0) { return rv; } } sleep_ms(200); return fd; } static volatile long syz_usb_connect(volatile long a0, volatile long a1, volatile long a2, volatile long a3) { uint64_t speed = a0; uint64_t dev_len = a1; const char* dev = (const char*)a2; const struct vusb_connect_descriptors* descs = (const struct vusb_connect_descriptors*)a3; return syz_usb_connect_impl(speed, dev_len, dev, descs, &lookup_connect_response_out_generic); } static void kill_and_wait(int pid, int* status) { kill(-pid, SIGKILL); kill(pid, SIGKILL); for (int i = 0; i < 100; i++) { if (waitpid(-1, status, WNOHANG | __WALL) == pid) return; usleep(1000); } DIR* dir = opendir("/sys/fs/fuse/connections"); if (dir) { for (;;) { struct dirent* ent = readdir(dir); if (!ent) break; if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue; char abort[300]; snprintf(abort, sizeof(abort), "/sys/fs/fuse/connections/%s/abort", ent->d_name); int fd = open(abort, O_WRONLY); if (fd == -1) { continue; } if (write(fd, abort, 1) < 0) { } close(fd); } closedir(dir); } else { } while (waitpid(-1, status, __WALL) != pid) { } } static void setup_test() { prctl(PR_SET_PDEATHSIG, SIGKILL, 0, 0, 0); setpgrp(); write_file("/proc/self/oom_score_adj", "1000"); } static void execute_one(void); #define WAIT_FLAGS __WALL static void loop(void) { int iter = 0; for (;; iter++) { int pid = fork(); if (pid < 0) exit(1); if (pid == 0) { setup_test(); execute_one(); exit(0); } int status = 0; uint64_t start = current_time_ms(); for (;;) { if (waitpid(-1, &status, WNOHANG | WAIT_FLAGS) == pid) break; sleep_ms(1); if (current_time_ms() - start < 5000) { continue; } kill_and_wait(pid, &status); break; } } } void execute_one(void) { *(uint8_t*)0x200005c0 = 0x12; *(uint8_t*)0x200005c1 = 1; *(uint16_t*)0x200005c2 = 0x200; *(uint8_t*)0x200005c4 = 0x78; *(uint8_t*)0x200005c5 = 0x84; *(uint8_t*)0x200005c6 = 0xc4; *(uint8_t*)0x200005c7 = 8; *(uint16_t*)0x200005c8 = 0x1964; *(uint16_t*)0x200005ca = 1; *(uint16_t*)0x200005cc = 0x526b; *(uint8_t*)0x200005ce = 1; *(uint8_t*)0x200005cf = 2; *(uint8_t*)0x200005d0 = 3; *(uint8_t*)0x200005d1 = 1; *(uint8_t*)0x200005d2 = 9; *(uint8_t*)0x200005d3 = 2; *(uint16_t*)0x200005d4 = 0x34c; *(uint8_t*)0x200005d6 = 4; *(uint8_t*)0x200005d7 = 0x81; *(uint8_t*)0x200005d8 = 0; *(uint8_t*)0x200005d9 = 0x80; *(uint8_t*)0x200005da = 0x1f; *(uint8_t*)0x200005db = 9; *(uint8_t*)0x200005dc = 4; *(uint8_t*)0x200005dd = 0x4f; *(uint8_t*)0x200005de = 0x81; *(uint8_t*)0x200005df = 0x10; *(uint8_t*)0x200005e0 = 0x22; *(uint8_t*)0x200005e1 = 0x7f; *(uint8_t*)0x200005e2 = 0x4b; *(uint8_t*)0x200005e3 = 0; *(uint8_t*)0x200005e4 = 5; *(uint8_t*)0x200005e5 = 0x24; *(uint8_t*)0x200005e6 = 6; *(uint8_t*)0x200005e7 = 0; *(uint8_t*)0x200005e8 = 1; *(uint8_t*)0x200005e9 = 5; *(uint8_t*)0x200005ea = 0x24; *(uint8_t*)0x200005eb = 0; *(uint16_t*)0x200005ec = 1; *(uint8_t*)0x200005ee = 0xd; *(uint8_t*)0x200005ef = 0x24; *(uint8_t*)0x200005f0 = 0xf; *(uint8_t*)0x200005f1 = 1; *(uint32_t*)0x200005f2 = 3; *(uint16_t*)0x200005f6 = 4; *(uint16_t*)0x200005f8 = 0x1f; *(uint8_t*)0x200005fa = 0x81; *(uint8_t*)0x200005fb = 6; *(uint8_t*)0x200005fc = 0x24; *(uint8_t*)0x200005fd = 0x1a; *(uint16_t*)0x200005fe = 8; *(uint8_t*)0x20000600 = 7; *(uint8_t*)0x20000601 = 9; *(uint8_t*)0x20000602 = 5; *(uint8_t*)0x20000603 = 6; *(uint8_t*)0x20000604 = 1; *(uint16_t*)0x20000605 = 0x20; *(uint8_t*)0x20000607 = 2; *(uint8_t*)0x20000608 = 3; *(uint8_t*)0x20000609 = 7; *(uint8_t*)0x2000060a = 9; *(uint8_t*)0x2000060b = 5; *(uint8_t*)0x2000060c = 9; *(uint8_t*)0x2000060d = 2; *(uint16_t*)0x2000060e = 0x200; *(uint8_t*)0x20000610 = 8; *(uint8_t*)0x20000611 = 6; *(uint8_t*)0x20000612 = 0x80; *(uint8_t*)0x20000613 = 7; *(uint8_t*)0x20000614 = 0x25; *(uint8_t*)0x20000615 = 1; *(uint8_t*)0x20000616 = 1; *(uint8_t*)0x20000617 = 0x81; *(uint16_t*)0x20000618 = 1; *(uint8_t*)0x2000061a = 2; *(uint8_t*)0x2000061b = 0x23; *(uint8_t*)0x2000061c = 9; *(uint8_t*)0x2000061d = 5; *(uint8_t*)0x2000061e = 6; *(uint8_t*)0x2000061f = 1; *(uint16_t*)0x20000620 = 0x200; *(uint8_t*)0x20000622 = 0x40; *(uint8_t*)0x20000623 = 6; *(uint8_t*)0x20000624 = 8; *(uint8_t*)0x20000625 = 9; *(uint8_t*)0x20000626 = 5; *(uint8_t*)0x20000627 = 1; *(uint8_t*)0x20000628 = 0x10; *(uint16_t*)0x20000629 = 8; *(uint8_t*)0x2000062b = 0; *(uint8_t*)0x2000062c = 0x7f; *(uint8_t*)0x2000062d = 0x49; *(uint8_t*)0x2000062e = 9; *(uint8_t*)0x2000062f = 5; *(uint8_t*)0x20000630 = 0xd; *(uint8_t*)0x20000631 = 1; *(uint16_t*)0x20000632 = 0x20; *(uint8_t*)0x20000634 = 6; *(uint8_t*)0x20000635 = 0x40; *(uint8_t*)0x20000636 = 0xfc; *(uint8_t*)0x20000637 = 9; *(uint8_t*)0x20000638 = 5; *(uint8_t*)0x20000639 = 8; *(uint8_t*)0x2000063a = 0x10; *(uint16_t*)0x2000063b = 0x20; *(uint8_t*)0x2000063d = 1; *(uint8_t*)0x2000063e = 5; *(uint8_t*)0x2000063f = 0xf6; *(uint8_t*)0x20000640 = 2; *(uint8_t*)0x20000641 = 0xf; *(uint8_t*)0x20000642 = 2; *(uint8_t*)0x20000643 = 0x10; *(uint8_t*)0x20000644 = 9; *(uint8_t*)0x20000645 = 5; *(uint8_t*)0x20000646 = 0xa; *(uint8_t*)0x20000647 = 0x10; *(uint16_t*)0x20000648 = 0x200; *(uint8_t*)0x2000064a = 2; *(uint8_t*)0x2000064b = 0; *(uint8_t*)0x2000064c = 0; *(uint8_t*)0x2000064d = 2; *(uint8_t*)0x2000064e = 0xa; *(uint8_t*)0x2000064f = 9; *(uint8_t*)0x20000650 = 5; *(uint8_t*)0x20000651 = 0; *(uint8_t*)0x20000652 = 0; *(uint16_t*)0x20000653 = 8; *(uint8_t*)0x20000655 = 0x7f; *(uint8_t*)0x20000656 = 0x80; *(uint8_t*)0x20000657 = 0x81; *(uint8_t*)0x20000658 = 9; *(uint8_t*)0x20000659 = 5; *(uint8_t*)0x2000065a = 7; *(uint8_t*)0x2000065b = 0; *(uint16_t*)0x2000065c = 0x3ff; *(uint8_t*)0x2000065e = 5; *(uint8_t*)0x2000065f = 0x1f; *(uint8_t*)0x20000660 = 0xfb; *(uint8_t*)0x20000661 = 2; *(uint8_t*)0x20000662 = 0xe; *(uint8_t*)0x20000663 = 9; *(uint8_t*)0x20000664 = 5; *(uint8_t*)0x20000665 = 0; *(uint8_t*)0x20000666 = 2; *(uint16_t*)0x20000667 = 0x10; *(uint8_t*)0x20000669 = 4; *(uint8_t*)0x2000066a = 1; *(uint8_t*)0x2000066b = 8; *(uint8_t*)0x2000066c = 9; *(uint8_t*)0x2000066d = 5; *(uint8_t*)0x2000066e = 4; *(uint8_t*)0x2000066f = 2; *(uint16_t*)0x20000670 = 8; *(uint8_t*)0x20000672 = -1; *(uint8_t*)0x20000673 = 0x7f; *(uint8_t*)0x20000674 = 0x40; *(uint8_t*)0x20000675 = 7; *(uint8_t*)0x20000676 = 0x25; *(uint8_t*)0x20000677 = 1; *(uint8_t*)0x20000678 = 0; *(uint8_t*)0x20000679 = 8; *(uint16_t*)0x2000067a = 8; *(uint8_t*)0x2000067c = 9; *(uint8_t*)0x2000067d = 5; *(uint8_t*)0x2000067e = 8; *(uint8_t*)0x2000067f = 4; *(uint16_t*)0x20000680 = 0x20; *(uint8_t*)0x20000682 = 0x3d; *(uint8_t*)0x20000683 = 0x50; *(uint8_t*)0x20000684 = 5; *(uint8_t*)0x20000685 = 9; *(uint8_t*)0x20000686 = 5; *(uint8_t*)0x20000687 = 0x80; *(uint8_t*)0x20000688 = 0; *(uint16_t*)0x20000689 = 0x400; *(uint8_t*)0x2000068b = 0x80; *(uint8_t*)0x2000068c = 2; *(uint8_t*)0x2000068d = 6; *(uint8_t*)0x2000068e = 9; *(uint8_t*)0x2000068f = 5; *(uint8_t*)0x20000690 = 2; *(uint8_t*)0x20000691 = 0x10; *(uint16_t*)0x20000692 = 0x3ff; *(uint8_t*)0x20000694 = 5; *(uint8_t*)0x20000695 = 0; *(uint8_t*)0x20000696 = 3; *(uint8_t*)0x20000697 = 2; *(uint8_t*)0x20000698 = 0x31; *(uint8_t*)0x20000699 = 9; *(uint8_t*)0x2000069a = 5; *(uint8_t*)0x2000069b = 0x80; *(uint8_t*)0x2000069c = 0; *(uint16_t*)0x2000069d = 0x458; *(uint8_t*)0x2000069f = 0; *(uint8_t*)0x200006a0 = 1; *(uint8_t*)0x200006a1 = 8; *(uint8_t*)0x200006a2 = 2; *(uint8_t*)0x200006a3 = 0x23; *(uint8_t*)0x200006a4 = 2; *(uint8_t*)0x200006a5 = 2; *(uint8_t*)0x200006a6 = 9; *(uint8_t*)0x200006a7 = 5; *(uint8_t*)0x200006a8 = 8; *(uint8_t*)0x200006a9 = 0x92; *(uint16_t*)0x200006aa = 0x10; *(uint8_t*)0x200006ac = 0x1f; *(uint8_t*)0x200006ad = 2; *(uint8_t*)0x200006ae = 1; *(uint8_t*)0x200006af = 2; *(uint8_t*)0x200006b0 = 0xd; *(uint8_t*)0x200006b1 = 2; *(uint8_t*)0x200006b2 = 0xb; *(uint8_t*)0x200006b3 = 9; *(uint8_t*)0x200006b4 = 4; *(uint8_t*)0x200006b5 = 1; *(uint8_t*)0x200006b6 = 0xe7; *(uint8_t*)0x200006b7 = 0x10; *(uint8_t*)0x200006b8 = 0xa8; *(uint8_t*)0x200006b9 = 0xcf; *(uint8_t*)0x200006ba = 0xdf; *(uint8_t*)0x200006bb = 7; *(uint8_t*)0x200006bc = 5; *(uint8_t*)0x200006bd = 0x24; *(uint8_t*)0x200006be = 6; *(uint8_t*)0x200006bf = 0; *(uint8_t*)0x200006c0 = 0; *(uint8_t*)0x200006c1 = 5; *(uint8_t*)0x200006c2 = 0x24; *(uint8_t*)0x200006c3 = 0; *(uint16_t*)0x200006c4 = 0xd1e8; *(uint8_t*)0x200006c6 = 0xd; *(uint8_t*)0x200006c7 = 0x24; *(uint8_t*)0x200006c8 = 0xf; *(uint8_t*)0x200006c9 = 1; *(uint32_t*)0x200006ca = 0; *(uint16_t*)0x200006ce = 0; *(uint16_t*)0x200006d0 = 0xfff; *(uint8_t*)0x200006d2 = 0x81; *(uint8_t*)0x200006d3 = 4; *(uint8_t*)0x200006d4 = 0x24; *(uint8_t*)0x200006d5 = 2; *(uint8_t*)0x200006d6 = 0xc; *(uint8_t*)0x200006d7 = 7; *(uint8_t*)0x200006d8 = 0x24; *(uint8_t*)0x200006d9 = 0xa; *(uint8_t*)0x200006da = 6; *(uint8_t*)0x200006db = 0x80; *(uint8_t*)0x200006dc = 0x40; *(uint8_t*)0x200006dd = 6; *(uint8_t*)0x200006de = 9; *(uint8_t*)0x200006df = 5; *(uint8_t*)0x200006e0 = 5; *(uint8_t*)0x200006e1 = 0; *(uint16_t*)0x200006e2 = 0x10; *(uint8_t*)0x200006e4 = 0x40; *(uint8_t*)0x200006e5 = 0x1f; *(uint8_t*)0x200006e6 = 3; *(uint8_t*)0x200006e7 = 9; *(uint8_t*)0x200006e8 = 5; *(uint8_t*)0x200006e9 = 1; *(uint8_t*)0x200006ea = 0; *(uint16_t*)0x200006eb = 8; *(uint8_t*)0x200006ed = 0x1f; *(uint8_t*)0x200006ee = 5; *(uint8_t*)0x200006ef = 6; *(uint8_t*)0x200006f0 = 7; *(uint8_t*)0x200006f1 = 0x25; *(uint8_t*)0x200006f2 = 1; *(uint8_t*)0x200006f3 = 3; *(uint8_t*)0x200006f4 = 0x20; *(uint16_t*)0x200006f5 = 0xfff; *(uint8_t*)0x200006f7 = 2; *(uint8_t*)0x200006f8 = 0xc; *(uint8_t*)0x200006f9 = 9; *(uint8_t*)0x200006fa = 5; *(uint8_t*)0x200006fb = 0xa; *(uint8_t*)0x200006fc = 8; *(uint16_t*)0x200006fd = 0x200; *(uint8_t*)0x200006ff = 3; *(uint8_t*)0x20000700 = 0x5a; *(uint8_t*)0x20000701 = 2; *(uint8_t*)0x20000702 = 2; *(uint8_t*)0x20000703 = 8; *(uint8_t*)0x20000704 = 9; *(uint8_t*)0x20000705 = 5; *(uint8_t*)0x20000706 = 0xe; *(uint8_t*)0x20000707 = 0x10; *(uint16_t*)0x20000708 = 0x400; *(uint8_t*)0x2000070a = 0x1e; *(uint8_t*)0x2000070b = 9; *(uint8_t*)0x2000070c = 0x7f; *(uint8_t*)0x2000070d = 7; *(uint8_t*)0x2000070e = 0x25; *(uint8_t*)0x2000070f = 1; *(uint8_t*)0x20000710 = 2; *(uint8_t*)0x20000711 = 0x29; *(uint16_t*)0x20000712 = 7; *(uint8_t*)0x20000714 = 9; *(uint8_t*)0x20000715 = 5; *(uint8_t*)0x20000716 = 7; *(uint8_t*)0x20000717 = 0; *(uint16_t*)0x20000718 = 0x200; *(uint8_t*)0x2000071a = 0xbf; *(uint8_t*)0x2000071b = 4; *(uint8_t*)0x2000071c = 4; *(uint8_t*)0x2000071d = 2; *(uint8_t*)0x2000071e = 0xe; *(uint8_t*)0x2000071f = 9; *(uint8_t*)0x20000720 = 5; *(uint8_t*)0x20000721 = 2; *(uint8_t*)0x20000722 = 0x10; *(uint16_t*)0x20000723 = 0x3ff; *(uint8_t*)0x20000725 = 0x1f; *(uint8_t*)0x20000726 = 0xf9; *(uint8_t*)0x20000727 = 2; *(uint8_t*)0x20000728 = 7; *(uint8_t*)0x20000729 = 0x25; *(uint8_t*)0x2000072a = 1; *(uint8_t*)0x2000072b = 1; *(uint8_t*)0x2000072c = 6; *(uint16_t*)0x2000072d = 0; *(uint8_t*)0x2000072f = 9; *(uint8_t*)0x20000730 = 5; *(uint8_t*)0x20000731 = 0xa; *(uint8_t*)0x20000732 = 0x10; *(uint16_t*)0x20000733 = 0x10; *(uint8_t*)0x20000735 = 4; *(uint8_t*)0x20000736 = 2; *(uint8_t*)0x20000737 = 2; *(uint8_t*)0x20000738 = 7; *(uint8_t*)0x20000739 = 0x25; *(uint8_t*)0x2000073a = 1; *(uint8_t*)0x2000073b = 2; *(uint8_t*)0x2000073c = 4; *(uint16_t*)0x2000073d = 1; *(uint8_t*)0x2000073f = 2; *(uint8_t*)0x20000740 = 7; *(uint8_t*)0x20000741 = 9; *(uint8_t*)0x20000742 = 5; *(uint8_t*)0x20000743 = 0xd; *(uint8_t*)0x20000744 = 1; *(uint16_t*)0x20000745 = 0x400; *(uint8_t*)0x20000747 = 5; *(uint8_t*)0x20000748 = 8; *(uint8_t*)0x20000749 = 0x20; *(uint8_t*)0x2000074a = 9; *(uint8_t*)0x2000074b = 5; *(uint8_t*)0x2000074c = 0xc; *(uint8_t*)0x2000074d = 0; *(uint16_t*)0x2000074e = 0x10; *(uint8_t*)0x20000750 = 0x81; *(uint8_t*)0x20000751 = 0x33; *(uint8_t*)0x20000752 = 9; *(uint8_t*)0x20000753 = 7; *(uint8_t*)0x20000754 = 0x25; *(uint8_t*)0x20000755 = 1; *(uint8_t*)0x20000756 = 1; *(uint8_t*)0x20000757 = 0; *(uint16_t*)0x20000758 = 4; *(uint8_t*)0x2000075a = 9; *(uint8_t*)0x2000075b = 5; *(uint8_t*)0x2000075c = 0xa; *(uint8_t*)0x2000075d = 0x10; *(uint16_t*)0x2000075e = 0x20; *(uint8_t*)0x20000760 = 0x1f; *(uint8_t*)0x20000761 = 4; *(uint8_t*)0x20000762 = 2; *(uint8_t*)0x20000763 = 9; *(uint8_t*)0x20000764 = 5; *(uint8_t*)0x20000765 = 0xe; *(uint8_t*)0x20000766 = 0x10; *(uint16_t*)0x20000767 = 8; *(uint8_t*)0x20000769 = 1; *(uint8_t*)0x2000076a = 9; *(uint8_t*)0x2000076b = 7; *(uint8_t*)0x2000076c = 2; *(uint8_t*)0x2000076d = 0xd; *(uint8_t*)0x2000076e = 7; *(uint8_t*)0x2000076f = 0x25; *(uint8_t*)0x20000770 = 1; *(uint8_t*)0x20000771 = 2; *(uint8_t*)0x20000772 = 0x81; *(uint16_t*)0x20000773 = -1; *(uint8_t*)0x20000775 = 9; *(uint8_t*)0x20000776 = 5; *(uint8_t*)0x20000777 = 0xf; *(uint8_t*)0x20000778 = 0; *(uint16_t*)0x20000779 = 0x10; *(uint8_t*)0x2000077b = 0x95; *(uint8_t*)0x2000077c = 0x20; *(uint8_t*)0x2000077d = 0; *(uint8_t*)0x2000077e = 9; *(uint8_t*)0x2000077f = 5; *(uint8_t*)0x20000780 = 4; *(uint8_t*)0x20000781 = 0; *(uint16_t*)0x20000782 = 0x40; *(uint8_t*)0x20000784 = 8; *(uint8_t*)0x20000785 = -1; *(uint8_t*)0x20000786 = 7; *(uint8_t*)0x20000787 = 9; *(uint8_t*)0x20000788 = 5; *(uint8_t*)0x20000789 = 4; *(uint8_t*)0x2000078a = 0x10; *(uint16_t*)0x2000078b = 0x408; *(uint8_t*)0x2000078d = 0; *(uint8_t*)0x2000078e = 1; *(uint8_t*)0x2000078f = 0x12; *(uint8_t*)0x20000790 = 9; *(uint8_t*)0x20000791 = 5; *(uint8_t*)0x20000792 = 5; *(uint8_t*)0x20000793 = 0x10; *(uint16_t*)0x20000794 = 0x3ff; *(uint8_t*)0x20000796 = 0xfc; *(uint8_t*)0x20000797 = 9; *(uint8_t*)0x20000798 = 4; *(uint8_t*)0x20000799 = 7; *(uint8_t*)0x2000079a = 0x25; *(uint8_t*)0x2000079b = 1; *(uint8_t*)0x2000079c = 0; *(uint8_t*)0x2000079d = 7; *(uint16_t*)0x2000079e = 0xff8c; *(uint8_t*)0x200007a0 = 9; *(uint8_t*)0x200007a1 = 5; *(uint8_t*)0x200007a2 = 0xf; *(uint8_t*)0x200007a3 = 1; *(uint16_t*)0x200007a4 = 0x3f7; *(uint8_t*)0x200007a6 = 0x40; *(uint8_t*)0x200007a7 = 0x70; *(uint8_t*)0x200007a8 = 0; *(uint8_t*)0x200007a9 = 7; *(uint8_t*)0x200007aa = 0x25; *(uint8_t*)0x200007ab = 1; *(uint8_t*)0x200007ac = 2; *(uint8_t*)0x200007ad = 0x1f; *(uint16_t*)0x200007ae = 0x1f; *(uint8_t*)0x200007b0 = 9; *(uint8_t*)0x200007b1 = 4; *(uint8_t*)0x200007b2 = 0x1c; *(uint8_t*)0x200007b3 = 8; *(uint8_t*)0x200007b4 = 0xf; *(uint8_t*)0x200007b5 = 0xc6; *(uint8_t*)0x200007b6 = 0x68; *(uint8_t*)0x200007b7 = 0x36; *(uint8_t*)0x200007b8 = 0x7f; *(uint8_t*)0x200007b9 = 9; *(uint8_t*)0x200007ba = 5; *(uint8_t*)0x200007bb = 8; *(uint8_t*)0x200007bc = 0; *(uint16_t*)0x200007bd = 0x200; *(uint8_t*)0x200007bf = -1; *(uint8_t*)0x200007c0 = 0x1f; *(uint8_t*)0x200007c1 = 5; *(uint8_t*)0x200007c2 = 7; *(uint8_t*)0x200007c3 = 0x25; *(uint8_t*)0x200007c4 = 1; *(uint8_t*)0x200007c5 = 0x82; *(uint8_t*)0x200007c6 = 3; *(uint16_t*)0x200007c7 = 0; *(uint8_t*)0x200007c9 = 7; *(uint8_t*)0x200007ca = 0x25; *(uint8_t*)0x200007cb = 1; *(uint8_t*)0x200007cc = 0x81; *(uint8_t*)0x200007cd = 2; *(uint16_t*)0x200007ce = 5; *(uint8_t*)0x200007d0 = 9; *(uint8_t*)0x200007d1 = 5; *(uint8_t*)0x200007d2 = 0xa; *(uint8_t*)0x200007d3 = 0xc; *(uint16_t*)0x200007d4 = 0x20; *(uint8_t*)0x200007d6 = 0x3f; *(uint8_t*)0x200007d7 = 0xa2; *(uint8_t*)0x200007d8 = 2; *(uint8_t*)0x200007d9 = 7; *(uint8_t*)0x200007da = 0x25; *(uint8_t*)0x200007db = 1; *(uint8_t*)0x200007dc = 2; *(uint8_t*)0x200007dd = 1; *(uint16_t*)0x200007de = 0x3f; *(uint8_t*)0x200007e0 = 2; *(uint8_t*)0x200007e1 = 0xf; *(uint8_t*)0x200007e2 = 9; *(uint8_t*)0x200007e3 = 5; *(uint8_t*)0x200007e4 = 0xa; *(uint8_t*)0x200007e5 = 0x10; *(uint16_t*)0x200007e6 = 0x200; *(uint8_t*)0x200007e8 = 0; *(uint8_t*)0x200007e9 = 0xc5; *(uint8_t*)0x200007ea = 0x40; *(uint8_t*)0x200007eb = 2; *(uint8_t*)0x200007ec = 0xd; *(uint8_t*)0x200007ed = 9; *(uint8_t*)0x200007ee = 5; *(uint8_t*)0x200007ef = 7; *(uint8_t*)0x200007f0 = 0x10; *(uint16_t*)0x200007f1 = 0x410; *(uint8_t*)0x200007f3 = 7; *(uint8_t*)0x200007f4 = 9; *(uint8_t*)0x200007f5 = 5; *(uint8_t*)0x200007f6 = 7; *(uint8_t*)0x200007f7 = 0x25; *(uint8_t*)0x200007f8 = 1; *(uint8_t*)0x200007f9 = 0x82; *(uint8_t*)0x200007fa = 2; *(uint16_t*)0x200007fb = 4; *(uint8_t*)0x200007fd = 9; *(uint8_t*)0x200007fe = 5; *(uint8_t*)0x200007ff = 9; *(uint8_t*)0x20000800 = 4; *(uint16_t*)0x20000801 = 0x200; *(uint8_t*)0x20000803 = 0x3f; *(uint8_t*)0x20000804 = 9; *(uint8_t*)0x20000805 = 0x7f; *(uint8_t*)0x20000806 = 9; *(uint8_t*)0x20000807 = 5; *(uint8_t*)0x20000808 = 0xa; *(uint8_t*)0x20000809 = 0x10; *(uint16_t*)0x2000080a = 0; *(uint8_t*)0x2000080c = 6; *(uint8_t*)0x2000080d = 7; *(uint8_t*)0x2000080e = 4; *(uint8_t*)0x2000080f = 7; *(uint8_t*)0x20000810 = 0x25; *(uint8_t*)0x20000811 = 1; *(uint8_t*)0x20000812 = 1; *(uint8_t*)0x20000813 = 0x3f; *(uint16_t*)0x20000814 = 8; *(uint8_t*)0x20000816 = 9; *(uint8_t*)0x20000817 = 5; *(uint8_t*)0x20000818 = 7; *(uint8_t*)0x20000819 = 0x10; *(uint16_t*)0x2000081a = 0x3ff; *(uint8_t*)0x2000081c = 0x7f; *(uint8_t*)0x2000081d = 0x40; *(uint8_t*)0x2000081e = 0xe0; *(uint8_t*)0x2000081f = 9; *(uint8_t*)0x20000820 = 5; *(uint8_t*)0x20000821 = 1; *(uint8_t*)0x20000822 = 8; *(uint16_t*)0x20000823 = 0x400; *(uint8_t*)0x20000825 = 7; *(uint8_t*)0x20000826 = 9; *(uint8_t*)0x20000827 = 0x7f; *(uint8_t*)0x20000828 = 7; *(uint8_t*)0x20000829 = 0x25; *(uint8_t*)0x2000082a = 1; *(uint8_t*)0x2000082b = 0; *(uint8_t*)0x2000082c = 0xf1; *(uint16_t*)0x2000082d = 0x8001; *(uint8_t*)0x2000082f = 9; *(uint8_t*)0x20000830 = 5; *(uint8_t*)0x20000831 = 0x80; *(uint8_t*)0x20000832 = 4; *(uint16_t*)0x20000833 = 0x20; *(uint8_t*)0x20000835 = 0xb5; *(uint8_t*)0x20000836 = 0x3c; *(uint8_t*)0x20000837 = 4; *(uint8_t*)0x20000838 = 9; *(uint8_t*)0x20000839 = 5; *(uint8_t*)0x2000083a = 0xf; *(uint8_t*)0x2000083b = 3; *(uint16_t*)0x2000083c = 0x20; *(uint8_t*)0x2000083e = 9; *(uint8_t*)0x2000083f = 3; *(uint8_t*)0x20000840 = 0x80; *(uint8_t*)0x20000841 = 2; *(uint8_t*)0x20000842 = 4; *(uint8_t*)0x20000843 = 7; *(uint8_t*)0x20000844 = 0x25; *(uint8_t*)0x20000845 = 1; *(uint8_t*)0x20000846 = 3; *(uint8_t*)0x20000847 = 0x34; *(uint16_t*)0x20000848 = 0x89ec; *(uint8_t*)0x2000084a = 9; *(uint8_t*)0x2000084b = 5; *(uint8_t*)0x2000084c = 6; *(uint8_t*)0x2000084d = 8; *(uint16_t*)0x2000084e = 0x40; *(uint8_t*)0x20000850 = 0x89; *(uint8_t*)0x20000851 = 9; *(uint8_t*)0x20000852 = 9; *(uint8_t*)0x20000853 = 2; *(uint8_t*)0x20000854 = 0x21; *(uint8_t*)0x20000855 = 7; *(uint8_t*)0x20000856 = 0x25; *(uint8_t*)0x20000857 = 1; *(uint8_t*)0x20000858 = 0; *(uint8_t*)0x20000859 = 1; *(uint16_t*)0x2000085a = 5; *(uint8_t*)0x2000085c = 9; *(uint8_t*)0x2000085d = 5; *(uint8_t*)0x2000085e = 0xb; *(uint8_t*)0x2000085f = 0; *(uint16_t*)0x20000860 = 0x10; *(uint8_t*)0x20000862 = 8; *(uint8_t*)0x20000863 = 0xd; *(uint8_t*)0x20000864 = 1; *(uint8_t*)0x20000865 = 2; *(uint8_t*)0x20000866 = 0x2a; *(uint8_t*)0x20000867 = 7; *(uint8_t*)0x20000868 = 0x25; *(uint8_t*)0x20000869 = 1; *(uint8_t*)0x2000086a = 0x83; *(uint8_t*)0x2000086b = 0x43; *(uint16_t*)0x2000086c = 4; *(uint8_t*)0x2000086e = 9; *(uint8_t*)0x2000086f = 5; *(uint8_t*)0x20000870 = 9; *(uint8_t*)0x20000871 = 0x10; *(uint16_t*)0x20000872 = 0x20; *(uint8_t*)0x20000874 = 4; *(uint8_t*)0x20000875 = 5; *(uint8_t*)0x20000876 = 7; *(uint8_t*)0x20000877 = 9; *(uint8_t*)0x20000878 = 5; *(uint8_t*)0x20000879 = 0xe; *(uint8_t*)0x2000087a = 0; *(uint16_t*)0x2000087b = 0x40; *(uint8_t*)0x2000087d = 9; *(uint8_t*)0x2000087e = 3; *(uint8_t*)0x2000087f = -1; *(uint8_t*)0x20000880 = 2; *(uint8_t*)0x20000881 = 0x31; *(uint8_t*)0x20000882 = 7; *(uint8_t*)0x20000883 = 0x25; *(uint8_t*)0x20000884 = 1; *(uint8_t*)0x20000885 = 0x82; *(uint8_t*)0x20000886 = 2; *(uint16_t*)0x20000887 = 2; *(uint8_t*)0x20000889 = 9; *(uint8_t*)0x2000088a = 5; *(uint8_t*)0x2000088b = 3; *(uint8_t*)0x2000088c = 0x10; *(uint16_t*)0x2000088d = 0x10; *(uint8_t*)0x2000088f = 7; *(uint8_t*)0x20000890 = 0xbc; *(uint8_t*)0x20000891 = 8; *(uint8_t*)0x20000892 = 9; *(uint8_t*)0x20000893 = 4; *(uint8_t*)0x20000894 = 0xe9; *(uint8_t*)0x20000895 = 0; *(uint8_t*)0x20000896 = 9; *(uint8_t*)0x20000897 = 0xc7; *(uint8_t*)0x20000898 = 0x6c; *(uint8_t*)0x20000899 = 0xe1; *(uint8_t*)0x2000089a = 0xfe; *(uint8_t*)0x2000089b = 9; *(uint8_t*)0x2000089c = 5; *(uint8_t*)0x2000089d = 7; *(uint8_t*)0x2000089e = 4; *(uint16_t*)0x2000089f = 0x10; *(uint8_t*)0x200008a1 = 0x5a; *(uint8_t*)0x200008a2 = 5; *(uint8_t*)0x200008a3 = 0x81; *(uint8_t*)0x200008a4 = 7; *(uint8_t*)0x200008a5 = 0x25; *(uint8_t*)0x200008a6 = 1; *(uint8_t*)0x200008a7 = 0x28; *(uint8_t*)0x200008a8 = 0x40; *(uint16_t*)0x200008a9 = 0x8c4b; *(uint8_t*)0x200008ab = 7; *(uint8_t*)0x200008ac = 0x25; *(uint8_t*)0x200008ad = 1; *(uint8_t*)0x200008ae = 3; *(uint8_t*)0x200008af = 9; *(uint16_t*)0x200008b0 = 3; *(uint8_t*)0x200008b2 = 9; *(uint8_t*)0x200008b3 = 5; *(uint8_t*)0x200008b4 = 9; *(uint8_t*)0x200008b5 = 0; *(uint16_t*)0x200008b6 = 0x400; *(uint8_t*)0x200008b8 = 1; *(uint8_t*)0x200008b9 = 0xf5; *(uint8_t*)0x200008ba = 0; *(uint8_t*)0x200008bb = 9; *(uint8_t*)0x200008bc = 5; *(uint8_t*)0x200008bd = 0; *(uint8_t*)0x200008be = 0x10; *(uint16_t*)0x200008bf = 0x3ff; *(uint8_t*)0x200008c1 = 8; *(uint8_t*)0x200008c2 = 0x40; *(uint8_t*)0x200008c3 = 5; *(uint8_t*)0x200008c4 = 7; *(uint8_t*)0x200008c5 = 0x25; *(uint8_t*)0x200008c6 = 1; *(uint8_t*)0x200008c7 = 1; *(uint8_t*)0x200008c8 = 0x80; *(uint16_t*)0x200008c9 = 3; *(uint8_t*)0x200008cb = 7; *(uint8_t*)0x200008cc = 0x25; *(uint8_t*)0x200008cd = 1; *(uint8_t*)0x200008ce = 3; *(uint8_t*)0x200008cf = 0xf8; *(uint16_t*)0x200008d0 = 7; *(uint8_t*)0x200008d2 = 9; *(uint8_t*)0x200008d3 = 5; *(uint8_t*)0x200008d4 = 4; *(uint8_t*)0x200008d5 = 0x10; *(uint16_t*)0x200008d6 = 0x3ff; *(uint8_t*)0x200008d8 = 0xf0; *(uint8_t*)0x200008d9 = 0x3f; *(uint8_t*)0x200008da = 3; *(uint8_t*)0x200008db = 9; *(uint8_t*)0x200008dc = 5; *(uint8_t*)0x200008dd = 7; *(uint8_t*)0x200008de = 0x10; *(uint16_t*)0x200008df = 0x3ff; *(uint8_t*)0x200008e1 = 5; *(uint8_t*)0x200008e2 = 0; *(uint8_t*)0x200008e3 = 3; *(uint8_t*)0x200008e4 = 2; *(uint8_t*)0x200008e5 = 0x23; *(uint8_t*)0x200008e6 = 2; *(uint8_t*)0x200008e7 = 0x30; *(uint8_t*)0x200008e8 = 9; *(uint8_t*)0x200008e9 = 5; *(uint8_t*)0x200008ea = 0x80; *(uint8_t*)0x200008eb = 3; *(uint16_t*)0x200008ec = 0x3ff; *(uint8_t*)0x200008ee = 0xaa; *(uint8_t*)0x200008ef = 0; *(uint8_t*)0x200008f0 = 2; *(uint8_t*)0x200008f1 = 2; *(uint8_t*)0x200008f2 = 0xe; *(uint8_t*)0x200008f3 = 9; *(uint8_t*)0x200008f4 = 5; *(uint8_t*)0x200008f5 = 6; *(uint8_t*)0x200008f6 = 7; *(uint16_t*)0x200008f7 = 0x20; *(uint8_t*)0x200008f9 = 0x17; *(uint8_t*)0x200008fa = 0x20; *(uint8_t*)0x200008fb = 4; *(uint8_t*)0x200008fc = 9; *(uint8_t*)0x200008fd = 5; *(uint8_t*)0x200008fe = 0; *(uint8_t*)0x200008ff = 0; *(uint16_t*)0x20000900 = 0x3af; *(uint8_t*)0x20000902 = 2; *(uint8_t*)0x20000903 = 1; *(uint8_t*)0x20000904 = 0xfb; *(uint8_t*)0x20000905 = 7; *(uint8_t*)0x20000906 = 0x25; *(uint8_t*)0x20000907 = 1; *(uint8_t*)0x20000908 = 2; *(uint8_t*)0x20000909 = 7; *(uint16_t*)0x2000090a = 3; *(uint8_t*)0x2000090c = 9; *(uint8_t*)0x2000090d = 5; *(uint8_t*)0x2000090e = 5; *(uint8_t*)0x2000090f = 8; *(uint16_t*)0x20000910 = 0x20; *(uint8_t*)0x20000912 = 0x20; *(uint8_t*)0x20000913 = 0; *(uint8_t*)0x20000914 = -1; *(uint8_t*)0x20000915 = 7; *(uint8_t*)0x20000916 = 0x25; *(uint8_t*)0x20000917 = 1; *(uint8_t*)0x20000918 = 0x81; *(uint8_t*)0x20000919 = 0x3f; *(uint16_t*)0x2000091a = 0; *(uint8_t*)0x2000091c = 2; *(uint8_t*)0x2000091d = 0x10; syz_usb_connect(0, 0x35e, 0x200005c0, 0); } int main(void) { syscall(__NR_mmap, 0x1ffff000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul); syscall(__NR_mmap, 0x20000000ul, 0x1000000ul, 7ul, 0x32ul, -1, 0ul); syscall(__NR_mmap, 0x21000000ul, 0x1000ul, 0ul, 0x32ul, -1, 0ul); loop(); return 0; }
the_stack_data/107952048.c
#include <stdio.h> typedef struct { double r; double i; } Complex; Complex cmul(Complex x, Complex y) { return (Complex){ .r = x.r * y.r - x.i * y.i, .i = x.r * y.i + y.r * x.i, }; } Complex fast_cpow(Complex c, unsigned n) { Complex a = {.r = 1, .i = 0}; while (n) { if (n % 2) { a = cmul(a, c); --n; } else { c = cmul(c, c); n >>= 1; } } return a; } int main(void) { Complex c; double x, y; unsigned n; printf("x = "); if (scanf("%lf", &x) != 1) { return 1; } printf("y = "); if (scanf("%lf", &y) != 1) { return 1; } printf("n = "); if (scanf("%u", &n) != 1) { return 1; } c = fast_cpow((Complex){.r = x, .i = y}, n); if (c.r && c.i) { printf("(x+iy)^n = %.37g+%.37gi\n", c.r, c.i); } else if (c.i) { printf("(x+iy)^n = %.37gi\n", c.i); } else { printf("(x+iy)^n = %.37g\n", c.r); } return 0; }
the_stack_data/63577.c
#include <stdio.h> #include <stdlib.h> typedef struct { int value; struct Node* left; struct Node* right; }Node; void preOrder(Node* n){ if( n != NULL){ printf("%i ", n->value); preOrder(n->left); preOrder(n->right); } } void inOrder(Node* n){ if( n != NULL) { inOrder(n->left); printf("%i ", n->value); inOrder(n->right); } } void postOrder(Node* n){ if( n != NULL) { postOrder(n->left); postOrder(n->right); printf("%i ", n->value); } } void searchNode(Node* n, int searchedValue){ if (n != NULL){ if (searchedValue == n->value){ printf("\nValor encontrado"); }else if (searchedValue < n->value){ searchNode(n->left, searchedValue); }else if (searchedValue > n->value){ searchNode(n->right, searchedValue); } }else{ printf("\n NAO ENCONTRADO"); } } void main(){ Node* n = (Node*) malloc(sizeof(Node)); Node* n1 = (Node*) malloc(sizeof(Node)); Node* n2 = (Node*) malloc(sizeof(Node)); n->value = 10; n1->value = 20; n1->left = NULL; n1->right = NULL; n2->value = 30; n2->left = NULL; n2->right = NULL; n->left = n1; n->right = n2; printf("\nPre-Ordem:"); preOrder(n); searchNode(n, 10); free(n); free(n1); free(n2); }
the_stack_data/950729.c
/* This testcase is part of GDB, the GNU debugger. Copyright 2013-2019 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ void subr (int parm) { } void end (void) { } int main () { subr (1); end (); }
the_stack_data/44231.c
#include<stdio.h> int n,m; //size of the matrix // This function does Binary search for x in i-th row from j_low to j_high. void binarySearch(int mat[n][m], int i, int j_low,int j_high, int x) { while (j_low <= j_high) { int j_mid = (j_low + j_high) / 2; // Element found if (mat[i][j_mid] == x){ printf("Found at (%d,%d)\n",i,j_mid); return ; } else if (mat[i][j_mid] > x) j_high = j_mid - 1; else j_low = j_mid + 1; } // element not found printf("element not found\n"); } // Function to perform binary search on the mid values of row to get the desired pair of rows // where the element can be found void modifiedBinarySearch(int mat[n][m], int n, int m, int x) { // If Single row matrix if (n == 1){ binarySearch(mat, 0, 0, m-1, x); return; } // Do binary search in middle column. // Condition to terminate the loop when the 2 desired rows are found. int i_low = 0, i_high = n-1, j_mid = m/2; while ((i_low+1) < i_high) { int i_mid = (i_low + i_high) / 2; // element found if (mat[i_mid][j_mid] == x){ printf("Found at (%d,%d)\n",i_mid,j_mid); return; } else if (mat[i_mid][j_mid] > x) i_high = i_mid; else i_low = i_mid; } // If element is present on the mid of the two rows if (mat[i_low][j_mid] == x) printf("Found at (%d,%d)\n",i_low,j_mid); else if (mat[i_low+1][j_mid] == x) printf("Found at (%d,%d)\n",i_low+1,j_mid); // Search element on 1st half of 1st row else if (x <= mat[i_low][j_mid-1]) binarySearch(mat, i_low, 0, j_mid-1, x); // Search element on 2nd half of 1st row else if (x >= mat[i_low][j_mid+1] && x <= mat[i_low][m-1]) binarySearch(mat, i_low, j_mid+1, m-1, x); // Search element on 1st half of 2nd row else if (x <= mat[i_low+1][j_mid-1]) binarySearch(mat, i_low+1, 0, j_mid-1, x); // search element on 2nd half of 2nd row else binarySearch(mat, i_low+1, j_mid+1, m-1, x); } int main() { int x; //element to be searched scanf("%d %d %d\n",&n,&m,&x); int mat[n][m]; for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ scanf("%d",&mat[i][j]); } } modifiedBinarySearch(mat, n, m, x); return 0; }
the_stack_data/881410.c
#include <stdio.h> typedef struct _Candidato Candidato; struct _Candidato { int id_inscricao; char curso[20]; char cpf[15]; char dataNacimento[11]; char sexo; char email[40]; char opcaoQuadro; }; int main() { FILE *candidatosA, *candidatosB; Candidato *a, *b; char *arquivoA = "candidatosA.dat"; char *arquivoB = "candidatosB.dat"; int cont = 0; candidatosA = fopen(arquivoA, "r"); candidatosB = fopen(arquivoB, "r"); if (candidatosA == NULL) { fprintf(stderr, "Erro ao abrir o %s.\n", arquivoA); return 1; } if (candidatosB == NULL) { fprintf(stderr, "Erro ao abrir o %s.\n", arquivoB); return 1; } while (!feof(candidatosA) && !feof(candidatosB)) { cont++; fread(&a, sizeof(Candidato), 1, candidatosA); fread(&b, sizeof(Candidato), 1, candidatosB); printf("Candidato %i do arquivo %s: email( %s ) \n",cont, arquivoA, a->email); printf("Candidato %i do arquivo %s: email( %s ) \n",cont, arquivoB, b->email); } while (!feof(candidatosA)) { cont++; fread(&a, sizeof(Candidato), 1, candidatosA); printf("Candidato %i do arquivo %s: email( %s ) \n",cont, arquivoA, a->email); } while (!feof(candidatosB)) { cont++; fread(&b, sizeof(Candidato), 1, candidatosB); printf("Candidato %i do arquivo %s: email( %s ) \n",cont, arquivoB, b->email); } fclose(candidatosA); fclose(candidatosB); return 0; }
the_stack_data/54824625.c
#include <stdio.h> #include<limits.h> #define INFY 999999999 long int m[20][20]; int s[20][20]; int p[20],i,j,n; void print_optimal(int i,int j) { if (i == j) printf(" A%d ",i); else { printf("( "); print_optimal(i, s[i][j]); print_optimal(s[i][j] + 1, j); printf(" )"); } } void matmultiply(void) { long int q; int k; for(i=n;i>0;i--) { for(j=i;j<=n;j++) { if(i==j) m[i][j]=0; else { for(k=i;k<j;k++) { q=m[i][k]+m[k+1][j]+p[i-1]*p[k]*p[j]; if(q<m[i][j]) { m[i][j]=q; s[i][j]=k; } } } } } } int MatrixChainOrder(int p[], int i, int j) { if(i == j) return 0; int k; int min = INT_MAX; int count; for (k = i; k <j; k++) { count = MatrixChainOrder(p, i, k) + MatrixChainOrder(p, k+1, j) + p[i-1]*p[k]*p[j]; if (count < min) min = count; } return min; } void main() { int k; printf("Enter the no. of elements: "); scanf("%d",&n); for(i=1;i<=n;i++) for(j=i+1;j<=n;j++) { m[i][i]=0; m[i][j]=INFY; s[i][j]=0; } printf("\nEnter the dimensions: \n"); for(k=0;k<=n;k++) { printf("P%d: ",k); scanf("%d",&p[k]); } matmultiply(); printf("\nCost Matrix M:\n"); for(i=1;i<=n;i++) for(j=i;j<=n;j++) printf("m[%d][%d]: %ld\n",i,j,m[i][j]); i=1,j=n; printf("\nMultiplication Sequence : "); print_optimal(i,j); printf("\nMinimum number of multiplications is : %d ",MatrixChainOrder(p, 1, n)); }
the_stack_data/847598.c
/** * Faça uma função que receba o número de termos ​n de fibonacci * e retorne os ​n termos da sequência de fibonacci */ #include <stdio.h> #include <stdlib.h> void fibonacci(int num); int main(int argc, char const *argv[]) { int numeros; printf("Digite o número de termos: "); scanf("%d", &numeros); fibonacci(numeros); printf("FIM"); return 0; } void fibonacci(int num) { int a, b, aux, i; a = 0; b = 1; if (num <= 0) { printf("Numero Invalido!"); } else if (num == 1) { printf("0\n"); } else if (num == 2) { printf("0\n"); printf("1\n"); } else { printf("0\n"); printf("1\n"); for (i = 2; i < num; i++) { aux = a + b; a = b; b = aux; printf("%d\n", aux); } } }
the_stack_data/193893571.c
/* { dg-do run } */ /* { dg-xfail-run-if "" { empty-*-* } { "*" } { "" } } */ extern void abort (void); int main () { return 0; /* This results in a pass. */ }
the_stack_data/152544.c
/* ** 2017-12-26 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file implements a virtual table for reading and writing ZIP archive ** files. ** ** Usage example: ** ** SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename); ** ** Current limitations: ** ** * No support for encryption ** * No support for ZIP archives spanning multiple files ** * No support for zip64 extensions ** * Only the "inflate/deflate" (zlib) compression method is supported */ #include "sqlite3ext.h" SQLITE_EXTENSION_INIT1 #include <stdio.h> #include <string.h> #include <assert.h> #include <zlib.h> #ifndef SQLITE_OMIT_VIRTUALTABLE #ifndef SQLITE_AMALGAMATION typedef sqlite3_int64 i64; typedef unsigned char u8; typedef unsigned short u16; typedef unsigned long u32; #define MIN(a,b) ((a)<(b) ? (a) : (b)) #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST) # define ALWAYS(X) (1) # define NEVER(X) (0) #elif !defined(NDEBUG) # define ALWAYS(X) ((X)?1:(assert(0),0)) # define NEVER(X) ((X)?(assert(0),1):0) #else # define ALWAYS(X) (X) # define NEVER(X) (X) #endif #endif /* SQLITE_AMALGAMATION */ /* ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK. ** ** In some ways it would be better to obtain these values from system ** header files. But, the dependency is undesirable and (a) these ** have been stable for decades, (b) the values are part of POSIX and ** are also made explicit in [man stat], and (c) are part of the ** file format for zip archives. */ #ifndef S_IFDIR # define S_IFDIR 0040000 #endif #ifndef S_IFREG # define S_IFREG 0100000 #endif #ifndef S_IFLNK # define S_IFLNK 0120000 #endif static const char ZIPFILE_SCHEMA[] = "CREATE TABLE y(" "name PRIMARY KEY," /* 0: Name of file in zip archive */ "mode," /* 1: POSIX mode for file */ "mtime," /* 2: Last modification time (secs since 1970)*/ "sz," /* 3: Size of object */ "rawdata," /* 4: Raw data */ "data," /* 5: Uncompressed data */ "method," /* 6: Compression method (integer) */ "z HIDDEN" /* 7: Name of zip file */ ") WITHOUT ROWID;"; #define ZIPFILE_F_COLUMN_IDX 7 /* Index of column "file" in the above */ #define ZIPFILE_BUFFER_SIZE (64*1024) /* ** Magic numbers used to read and write zip files. ** ** ZIPFILE_NEWENTRY_MADEBY: ** Use this value for the "version-made-by" field in new zip file ** entries. The upper byte indicates "unix", and the lower byte ** indicates that the zip file matches pkzip specification 3.0. ** This is what info-zip seems to do. ** ** ZIPFILE_NEWENTRY_REQUIRED: ** Value for "version-required-to-extract" field of new entries. ** Version 2.0 is required to support folders and deflate compression. ** ** ZIPFILE_NEWENTRY_FLAGS: ** Value for "general-purpose-bit-flags" field of new entries. Bit ** 11 means "utf-8 filename and comment". ** ** ZIPFILE_SIGNATURE_CDS: ** First 4 bytes of a valid CDS record. ** ** ZIPFILE_SIGNATURE_LFH: ** First 4 bytes of a valid LFH record. ** ** ZIPFILE_SIGNATURE_EOCD ** First 4 bytes of a valid EOCD record. */ #define ZIPFILE_EXTRA_TIMESTAMP 0x5455 #define ZIPFILE_NEWENTRY_MADEBY ((3<<8) + 30) #define ZIPFILE_NEWENTRY_REQUIRED 20 #define ZIPFILE_NEWENTRY_FLAGS 0x800 #define ZIPFILE_SIGNATURE_CDS 0x02014b50 #define ZIPFILE_SIGNATURE_LFH 0x04034b50 #define ZIPFILE_SIGNATURE_EOCD 0x06054b50 /* ** The sizes of the fixed-size part of each of the three main data ** structures in a zip archive. */ #define ZIPFILE_LFH_FIXED_SZ 30 #define ZIPFILE_EOCD_FIXED_SZ 22 #define ZIPFILE_CDS_FIXED_SZ 46 /* *** 4.3.16 End of central directory record: *** *** end of central dir signature 4 bytes (0x06054b50) *** number of this disk 2 bytes *** number of the disk with the *** start of the central directory 2 bytes *** total number of entries in the *** central directory on this disk 2 bytes *** total number of entries in *** the central directory 2 bytes *** size of the central directory 4 bytes *** offset of start of central *** directory with respect to *** the starting disk number 4 bytes *** .ZIP file comment length 2 bytes *** .ZIP file comment (variable size) */ typedef struct ZipfileEOCD ZipfileEOCD; struct ZipfileEOCD { u16 iDisk; u16 iFirstDisk; u16 nEntry; u16 nEntryTotal; u32 nSize; u32 iOffset; }; /* *** 4.3.12 Central directory structure: *** *** ... *** *** central file header signature 4 bytes (0x02014b50) *** version made by 2 bytes *** version needed to extract 2 bytes *** general purpose bit flag 2 bytes *** compression method 2 bytes *** last mod file time 2 bytes *** last mod file date 2 bytes *** crc-32 4 bytes *** compressed size 4 bytes *** uncompressed size 4 bytes *** file name length 2 bytes *** extra field length 2 bytes *** file comment length 2 bytes *** disk number start 2 bytes *** internal file attributes 2 bytes *** external file attributes 4 bytes *** relative offset of local header 4 bytes */ typedef struct ZipfileCDS ZipfileCDS; struct ZipfileCDS { u16 iVersionMadeBy; u16 iVersionExtract; u16 flags; u16 iCompression; u16 mTime; u16 mDate; u32 crc32; u32 szCompressed; u32 szUncompressed; u16 nFile; u16 nExtra; u16 nComment; u16 iDiskStart; u16 iInternalAttr; u32 iExternalAttr; u32 iOffset; char *zFile; /* Filename (sqlite3_malloc()) */ }; /* *** 4.3.7 Local file header: *** *** local file header signature 4 bytes (0x04034b50) *** version needed to extract 2 bytes *** general purpose bit flag 2 bytes *** compression method 2 bytes *** last mod file time 2 bytes *** last mod file date 2 bytes *** crc-32 4 bytes *** compressed size 4 bytes *** uncompressed size 4 bytes *** file name length 2 bytes *** extra field length 2 bytes *** */ typedef struct ZipfileLFH ZipfileLFH; struct ZipfileLFH { u16 iVersionExtract; u16 flags; u16 iCompression; u16 mTime; u16 mDate; u32 crc32; u32 szCompressed; u32 szUncompressed; u16 nFile; u16 nExtra; }; typedef struct ZipfileEntry ZipfileEntry; struct ZipfileEntry { ZipfileCDS cds; /* Parsed CDS record */ u32 mUnixTime; /* Modification time, in UNIX format */ u8 *aExtra; /* cds.nExtra+cds.nComment bytes of extra data */ i64 iDataOff; /* Offset to data in file (if aData==0) */ u8 *aData; /* cds.szCompressed bytes of compressed data */ ZipfileEntry *pNext; /* Next element in in-memory CDS */ }; /* ** Cursor type for zipfile tables. */ typedef struct ZipfileCsr ZipfileCsr; struct ZipfileCsr { sqlite3_vtab_cursor base; /* Base class - must be first */ i64 iId; /* Cursor ID */ u8 bEof; /* True when at EOF */ u8 bNoop; /* If next xNext() call is no-op */ /* Used outside of write transactions */ FILE *pFile; /* Zip file */ i64 iNextOff; /* Offset of next record in central directory */ ZipfileEOCD eocd; /* Parse of central directory record */ ZipfileEntry *pFreeEntry; /* Free this list when cursor is closed or reset */ ZipfileEntry *pCurrent; /* Current entry */ ZipfileCsr *pCsrNext; /* Next cursor on same virtual table */ }; typedef struct ZipfileTab ZipfileTab; struct ZipfileTab { sqlite3_vtab base; /* Base class - must be first */ char *zFile; /* Zip file this table accesses (may be NULL) */ sqlite3 *db; /* Host database connection */ u8 *aBuffer; /* Temporary buffer used for various tasks */ ZipfileCsr *pCsrList; /* List of cursors */ i64 iNextCsrid; /* The following are used by write transactions only */ ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */ ZipfileEntry *pLastEntry; /* Last element in pFirstEntry list */ FILE *pWriteFd; /* File handle open on zip archive */ i64 szCurrent; /* Current size of zip archive */ i64 szOrig; /* Size of archive at start of transaction */ }; /* ** Set the error message contained in context ctx to the results of ** vprintf(zFmt, ...). */ static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){ char *zMsg = 0; va_list ap; va_start(ap, zFmt); zMsg = sqlite3_vmprintf(zFmt, ap); sqlite3_result_error(ctx, zMsg, -1); sqlite3_free(zMsg); va_end(ap); } /* ** If string zIn is quoted, dequote it in place. Otherwise, if the string ** is not quoted, do nothing. */ static void zipfileDequote(char *zIn){ char q = zIn[0]; if( q=='"' || q=='\'' || q=='`' || q=='[' ){ int iIn = 1; int iOut = 0; if( q=='[' ) q = ']'; while( ALWAYS(zIn[iIn]) ){ char c = zIn[iIn++]; if( c==q && zIn[iIn++]!=q ) break; zIn[iOut++] = c; } zIn[iOut] = '\0'; } } /* ** Construct a new ZipfileTab virtual table object. ** ** argv[0] -> module name ("zipfile") ** argv[1] -> database name ** argv[2] -> table name ** argv[...] -> "column name" and other module argument fields. */ static int zipfileConnect( sqlite3 *db, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVtab, char **pzErr ){ int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE; int nFile = 0; const char *zFile = 0; ZipfileTab *pNew = 0; int rc; /* If the table name is not "zipfile", require that the argument be ** specified. This stops zipfile tables from being created as: ** ** CREATE VIRTUAL TABLE zzz USING zipfile(); ** ** It does not prevent: ** ** CREATE VIRTUAL TABLE zipfile USING zipfile(); */ assert( 0==sqlite3_stricmp(argv[0], "zipfile") ); if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){ *pzErr = sqlite3_mprintf("zipfile constructor requires one argument"); return SQLITE_ERROR; } if( argc>3 ){ zFile = argv[3]; nFile = (int)strlen(zFile)+1; } rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA); if( rc==SQLITE_OK ){ pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile); if( pNew==0 ) return SQLITE_NOMEM; memset(pNew, 0, nByte+nFile); pNew->db = db; pNew->aBuffer = (u8*)&pNew[1]; if( zFile ){ pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE]; memcpy(pNew->zFile, zFile, nFile); zipfileDequote(pNew->zFile); } } *ppVtab = (sqlite3_vtab*)pNew; return rc; } /* ** Free the ZipfileEntry structure indicated by the only argument. */ static void zipfileEntryFree(ZipfileEntry *p){ if( p ){ sqlite3_free(p->cds.zFile); sqlite3_free(p); } } /* ** Release resources that should be freed at the end of a write ** transaction. */ static void zipfileCleanupTransaction(ZipfileTab *pTab){ ZipfileEntry *pEntry; ZipfileEntry *pNext; if( pTab->pWriteFd ){ fclose(pTab->pWriteFd); pTab->pWriteFd = 0; } for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){ pNext = pEntry->pNext; zipfileEntryFree(pEntry); } pTab->pFirstEntry = 0; pTab->pLastEntry = 0; pTab->szCurrent = 0; pTab->szOrig = 0; } /* ** This method is the destructor for zipfile vtab objects. */ static int zipfileDisconnect(sqlite3_vtab *pVtab){ zipfileCleanupTransaction((ZipfileTab*)pVtab); sqlite3_free(pVtab); return SQLITE_OK; } /* ** Constructor for a new ZipfileCsr object. */ static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){ ZipfileTab *pTab = (ZipfileTab*)p; ZipfileCsr *pCsr; pCsr = sqlite3_malloc(sizeof(*pCsr)); *ppCsr = (sqlite3_vtab_cursor*)pCsr; if( pCsr==0 ){ return SQLITE_NOMEM; } memset(pCsr, 0, sizeof(*pCsr)); pCsr->iId = ++pTab->iNextCsrid; pCsr->pCsrNext = pTab->pCsrList; pTab->pCsrList = pCsr; return SQLITE_OK; } /* ** Reset a cursor back to the state it was in when first returned ** by zipfileOpen(). */ static void zipfileResetCursor(ZipfileCsr *pCsr){ ZipfileEntry *p; ZipfileEntry *pNext; pCsr->bEof = 0; if( pCsr->pFile ){ fclose(pCsr->pFile); pCsr->pFile = 0; zipfileEntryFree(pCsr->pCurrent); pCsr->pCurrent = 0; } for(p=pCsr->pFreeEntry; p; p=pNext){ pNext = p->pNext; zipfileEntryFree(p); } } /* ** Destructor for an ZipfileCsr. */ static int zipfileClose(sqlite3_vtab_cursor *cur){ ZipfileCsr *pCsr = (ZipfileCsr*)cur; ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab); ZipfileCsr **pp; zipfileResetCursor(pCsr); /* Remove this cursor from the ZipfileTab.pCsrList list. */ for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext)); *pp = pCsr->pCsrNext; sqlite3_free(pCsr); return SQLITE_OK; } /* ** Set the error message for the virtual table associated with cursor ** pCsr to the results of vprintf(zFmt, ...). */ static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){ va_list ap; va_start(ap, zFmt); sqlite3_free(pTab->base.zErrMsg); pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap); va_end(ap); } static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){ va_list ap; va_start(ap, zFmt); sqlite3_free(pCsr->base.pVtab->zErrMsg); pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap); va_end(ap); } /* ** Read nRead bytes of data from offset iOff of file pFile into buffer ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code ** otherwise. ** ** If an error does occur, output variable (*pzErrmsg) may be set to point ** to an English language error message. It is the responsibility of the ** caller to eventually free this buffer using ** sqlite3_free(). */ static int zipfileReadData( FILE *pFile, /* Read from this file */ u8 *aRead, /* Read into this buffer */ int nRead, /* Number of bytes to read */ i64 iOff, /* Offset to read from */ char **pzErrmsg /* OUT: Error message (from sqlite3_malloc) */ ){ size_t n; fseek(pFile, (long)iOff, SEEK_SET); n = fread(aRead, 1, nRead, pFile); if( (int)n!=nRead ){ *pzErrmsg = sqlite3_mprintf("error in fread()"); return SQLITE_ERROR; } return SQLITE_OK; } static int zipfileAppendData( ZipfileTab *pTab, const u8 *aWrite, int nWrite ){ size_t n; fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET); n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd); if( (int)n!=nWrite ){ pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()"); return SQLITE_ERROR; } pTab->szCurrent += nWrite; return SQLITE_OK; } /* ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf. */ static u16 zipfileGetU16(const u8 *aBuf){ return (aBuf[1] << 8) + aBuf[0]; } /* ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf. */ static u32 zipfileGetU32(const u8 *aBuf){ return ((u32)(aBuf[3]) << 24) + ((u32)(aBuf[2]) << 16) + ((u32)(aBuf[1]) << 8) + ((u32)(aBuf[0]) << 0); } /* ** Write a 16-bit little endiate integer into buffer aBuf. */ static void zipfilePutU16(u8 *aBuf, u16 val){ aBuf[0] = val & 0xFF; aBuf[1] = (val>>8) & 0xFF; } /* ** Write a 32-bit little endiate integer into buffer aBuf. */ static void zipfilePutU32(u8 *aBuf, u32 val){ aBuf[0] = val & 0xFF; aBuf[1] = (val>>8) & 0xFF; aBuf[2] = (val>>16) & 0xFF; aBuf[3] = (val>>24) & 0xFF; } #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) ) #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) ) #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; } #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; } /* ** Magic numbers used to read CDS records. */ #define ZIPFILE_CDS_NFILE_OFF 28 #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20 /* ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR ** if the record is not well-formed, or SQLITE_OK otherwise. */ static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){ u8 *aRead = aBuf; u32 sig = zipfileRead32(aRead); int rc = SQLITE_OK; if( sig!=ZIPFILE_SIGNATURE_CDS ){ rc = SQLITE_ERROR; }else{ pCDS->iVersionMadeBy = zipfileRead16(aRead); pCDS->iVersionExtract = zipfileRead16(aRead); pCDS->flags = zipfileRead16(aRead); pCDS->iCompression = zipfileRead16(aRead); pCDS->mTime = zipfileRead16(aRead); pCDS->mDate = zipfileRead16(aRead); pCDS->crc32 = zipfileRead32(aRead); pCDS->szCompressed = zipfileRead32(aRead); pCDS->szUncompressed = zipfileRead32(aRead); assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] ); pCDS->nFile = zipfileRead16(aRead); pCDS->nExtra = zipfileRead16(aRead); pCDS->nComment = zipfileRead16(aRead); pCDS->iDiskStart = zipfileRead16(aRead); pCDS->iInternalAttr = zipfileRead16(aRead); pCDS->iExternalAttr = zipfileRead32(aRead); pCDS->iOffset = zipfileRead32(aRead); assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] ); } return rc; } /* ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR ** if the record is not well-formed, or SQLITE_OK otherwise. */ static int zipfileReadLFH( u8 *aBuffer, ZipfileLFH *pLFH ){ u8 *aRead = aBuffer; int rc = SQLITE_OK; u32 sig = zipfileRead32(aRead); if( sig!=ZIPFILE_SIGNATURE_LFH ){ rc = SQLITE_ERROR; }else{ pLFH->iVersionExtract = zipfileRead16(aRead); pLFH->flags = zipfileRead16(aRead); pLFH->iCompression = zipfileRead16(aRead); pLFH->mTime = zipfileRead16(aRead); pLFH->mDate = zipfileRead16(aRead); pLFH->crc32 = zipfileRead32(aRead); pLFH->szCompressed = zipfileRead32(aRead); pLFH->szUncompressed = zipfileRead32(aRead); pLFH->nFile = zipfileRead16(aRead); pLFH->nExtra = zipfileRead16(aRead); } return rc; } /* ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields. ** Scan through this buffer to find an "extra-timestamp" field. If one ** exists, extract the 32-bit modification-timestamp from it and store ** the value in output parameter *pmTime. ** ** Zero is returned if no extra-timestamp record could be found (and so ** *pmTime is left unchanged), or non-zero otherwise. ** ** The general format of an extra field is: ** ** Header ID 2 bytes ** Data Size 2 bytes ** Data N bytes */ static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){ int ret = 0; u8 *p = aExtra; u8 *pEnd = &aExtra[nExtra]; while( p<pEnd ){ u16 id = zipfileRead16(p); u16 nByte = zipfileRead16(p); switch( id ){ case ZIPFILE_EXTRA_TIMESTAMP: { u8 b = p[0]; if( b & 0x01 ){ /* 0x01 -> modtime is present */ *pmTime = zipfileGetU32(&p[1]); ret = 1; } break; } } p += nByte; } return ret; } /* ** Convert the standard MS-DOS timestamp stored in the mTime and mDate ** fields of the CDS structure passed as the only argument to a 32-bit ** UNIX seconds-since-the-epoch timestamp. Return the result. ** ** "Standard" MS-DOS time format: ** ** File modification time: ** Bits 00-04: seconds divided by 2 ** Bits 05-10: minute ** Bits 11-15: hour ** File modification date: ** Bits 00-04: day ** Bits 05-08: month (1-12) ** Bits 09-15: years from 1980 ** ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx */ static u32 zipfileMtime(ZipfileCDS *pCDS){ int Y = (1980 + ((pCDS->mDate >> 9) & 0x7F)); int M = ((pCDS->mDate >> 5) & 0x0F); int D = (pCDS->mDate & 0x1F); int B = -13; int sec = (pCDS->mTime & 0x1F)*2; int min = (pCDS->mTime >> 5) & 0x3F; int hr = (pCDS->mTime >> 11) & 0x1F; i64 JD; /* JD = INT(365.25 * (Y+4716)) + INT(30.6001 * (M+1)) + D + B - 1524.5 */ /* Calculate the JD in seconds for noon on the day in question */ if( M<3 ){ Y = Y-1; M = M+12; } JD = (i64)(24*60*60) * ( (int)(365.25 * (Y + 4716)) + (int)(30.6001 * (M + 1)) + D + B - 1524 ); /* Correct the JD for the time within the day */ JD += (hr-12) * 3600 + min * 60 + sec; /* Convert JD to unix timestamp (the JD epoch is 2440587.5) */ return (u32)(JD - (i64)(24405875) * 24*60*6); } /* ** The opposite of zipfileMtime(). This function populates the mTime and ** mDate fields of the CDS structure passed as the first argument according ** to the UNIX timestamp value passed as the second. */ static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){ /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */ i64 JD = (i64)2440588 + mUnixTime / (24*60*60); int A, B, C, D, E; int yr, mon, day; int hr, min, sec; A = (int)((JD - 1867216.25)/36524.25); A = (int)(JD + 1 + A - (A/4)); B = A + 1524; C = (int)((B - 122.1)/365.25); D = (36525*(C&32767))/100; E = (int)((B-D)/30.6001); day = B - D - (int)(30.6001*E); mon = (E<14 ? E-1 : E-13); yr = mon>2 ? C-4716 : C-4715; hr = (mUnixTime % (24*60*60)) / (60*60); min = (mUnixTime % (60*60)) / 60; sec = (mUnixTime % 60); if( yr>=1980 ){ pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9)); pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11)); }else{ pCds->mDate = pCds->mTime = 0; } assert( mUnixTime<315507600 || mUnixTime==zipfileMtime(pCds) || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds)) /* || (mUnixTime % 2) */ ); } /* ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in ** size) containing an entire zip archive image. Or, if aBlob is NULL, ** then pFile is a file-handle open on a zip file. In either case, this ** function creates a ZipfileEntry object based on the zip archive entry ** for which the CDS record is at offset iOff. ** ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to ** the new object. Otherwise, an SQLite error code is returned and the ** final value of (*ppEntry) undefined. */ static int zipfileGetEntry( ZipfileTab *pTab, /* Store any error message here */ const u8 *aBlob, /* Pointer to in-memory file image */ int nBlob, /* Size of aBlob[] in bytes */ FILE *pFile, /* If aBlob==0, read from this file */ i64 iOff, /* Offset of CDS record */ ZipfileEntry **ppEntry /* OUT: Pointer to new object */ ){ u8 *aRead; char **pzErr = &pTab->base.zErrMsg; int rc = SQLITE_OK; if( aBlob==0 ){ aRead = pTab->aBuffer; rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr); }else{ aRead = (u8*)&aBlob[iOff]; } if( rc==SQLITE_OK ){ sqlite3_int64 nAlloc; ZipfileEntry *pNew; int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]); int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]); nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]); nAlloc = sizeof(ZipfileEntry) + nExtra; if( aBlob ){ nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]); } pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc); if( pNew==0 ){ rc = SQLITE_NOMEM; }else{ memset(pNew, 0, sizeof(ZipfileEntry)); rc = zipfileReadCDS(aRead, &pNew->cds); if( rc!=SQLITE_OK ){ *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff); }else if( aBlob==0 ){ rc = zipfileReadData( pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr ); }else{ aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ]; } } if( rc==SQLITE_OK ){ u32 *pt = &pNew->mUnixTime; pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead); pNew->aExtra = (u8*)&pNew[1]; memcpy(pNew->aExtra, &aRead[nFile], nExtra); if( pNew->cds.zFile==0 ){ rc = SQLITE_NOMEM; }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){ pNew->mUnixTime = zipfileMtime(&pNew->cds); } } if( rc==SQLITE_OK ){ static const int szFix = ZIPFILE_LFH_FIXED_SZ; ZipfileLFH lfh; if( pFile ){ rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr); }else{ aRead = (u8*)&aBlob[pNew->cds.iOffset]; } rc = zipfileReadLFH(aRead, &lfh); if( rc==SQLITE_OK ){ pNew->iDataOff = pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ; pNew->iDataOff += lfh.nFile + lfh.nExtra; if( aBlob && pNew->cds.szCompressed ){ pNew->aData = &pNew->aExtra[nExtra]; memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed); } }else{ *pzErr = sqlite3_mprintf("failed to read LFH at offset %d", (int)pNew->cds.iOffset ); } } if( rc!=SQLITE_OK ){ zipfileEntryFree(pNew); }else{ *ppEntry = pNew; } } return rc; } /* ** Advance an ZipfileCsr to its next row of output. */ static int zipfileNext(sqlite3_vtab_cursor *cur){ ZipfileCsr *pCsr = (ZipfileCsr*)cur; int rc = SQLITE_OK; if( pCsr->pFile ){ i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize; zipfileEntryFree(pCsr->pCurrent); pCsr->pCurrent = 0; if( pCsr->iNextOff>=iEof ){ pCsr->bEof = 1; }else{ ZipfileEntry *p = 0; ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab); rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p); if( rc==SQLITE_OK ){ pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ; pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment; } pCsr->pCurrent = p; } }else{ if( !pCsr->bNoop ){ pCsr->pCurrent = pCsr->pCurrent->pNext; } if( pCsr->pCurrent==0 ){ pCsr->bEof = 1; } } pCsr->bNoop = 0; return rc; } static void zipfileFree(void *p) { sqlite3_free(p); } /* ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the ** size is nOut bytes. This function uncompresses the data and sets the ** return value in context pCtx to the result (a blob). ** ** If an error occurs, an error code is left in pCtx instead. */ static void zipfileInflate( sqlite3_context *pCtx, /* Store result here */ const u8 *aIn, /* Compressed data */ int nIn, /* Size of buffer aIn[] in bytes */ int nOut /* Expected output size */ ){ u8 *aRes = sqlite3_malloc(nOut); if( aRes==0 ){ sqlite3_result_error_nomem(pCtx); }else{ int err; z_stream str; memset(&str, 0, sizeof(str)); str.next_in = (Byte*)aIn; str.avail_in = nIn; str.next_out = (Byte*)aRes; str.avail_out = nOut; err = inflateInit2(&str, -15); if( err!=Z_OK ){ zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err); }else{ err = inflate(&str, Z_NO_FLUSH); if( err!=Z_STREAM_END ){ zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err); }else{ sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree); aRes = 0; } } sqlite3_free(aRes); inflateEnd(&str); } } /* ** Buffer aIn (size nIn bytes) contains uncompressed data. This function ** compresses it and sets (*ppOut) to point to a buffer containing the ** compressed data. The caller is responsible for eventually calling ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut) ** is set to the size of buffer (*ppOut) in bytes. ** ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error ** code is returned and an error message left in virtual-table handle ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this ** case. */ static int zipfileDeflate( const u8 *aIn, int nIn, /* Input */ u8 **ppOut, int *pnOut, /* Output */ char **pzErr /* OUT: Error message */ ){ int rc = SQLITE_OK; sqlite3_int64 nAlloc; z_stream str; u8 *aOut; memset(&str, 0, sizeof(str)); str.next_in = (Bytef*)aIn; str.avail_in = nIn; deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY); nAlloc = deflateBound(&str, nIn); aOut = (u8*)sqlite3_malloc64(nAlloc); if( aOut==0 ){ rc = SQLITE_NOMEM; }else{ int res; str.next_out = aOut; str.avail_out = nAlloc; deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY); res = deflate(&str, Z_FINISH); if( res==Z_STREAM_END ){ *ppOut = aOut; *pnOut = (int)str.total_out; }else{ sqlite3_free(aOut); *pzErr = sqlite3_mprintf("zipfile: deflate() error"); rc = SQLITE_ERROR; } deflateEnd(&str); } return rc; } /* ** Return values of columns for the row at which the series_cursor ** is currently pointing. */ static int zipfileColumn( sqlite3_vtab_cursor *cur, /* The cursor */ sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ int i /* Which column to return */ ){ ZipfileCsr *pCsr = (ZipfileCsr*)cur; ZipfileCDS *pCDS = &pCsr->pCurrent->cds; int rc = SQLITE_OK; switch( i ){ case 0: /* name */ sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT); break; case 1: /* mode */ /* TODO: Whether or not the following is correct surely depends on ** the platform on which the archive was created. */ sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16); break; case 2: { /* mtime */ sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime); break; } case 3: { /* sz */ if( sqlite3_vtab_nochange(ctx)==0 ){ sqlite3_result_int64(ctx, pCDS->szUncompressed); } break; } case 4: /* rawdata */ if( sqlite3_vtab_nochange(ctx) ) break; case 5: { /* data */ if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){ int sz = pCDS->szCompressed; int szFinal = pCDS->szUncompressed; if( szFinal>0 ){ u8 *aBuf; u8 *aFree = 0; if( pCsr->pCurrent->aData ){ aBuf = pCsr->pCurrent->aData; }else{ aBuf = aFree = sqlite3_malloc64(sz); if( aBuf==0 ){ rc = SQLITE_NOMEM; }else{ FILE *pFile = pCsr->pFile; if( pFile==0 ){ pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd; } rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff, &pCsr->base.pVtab->zErrMsg ); } } if( rc==SQLITE_OK ){ if( i==5 && pCDS->iCompression ){ zipfileInflate(ctx, aBuf, sz, szFinal); }else{ sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT); } } sqlite3_free(aFree); }else{ /* Figure out if this is a directory or a zero-sized file. Consider ** it to be a directory either if the mode suggests so, or if ** the final character in the name is '/'. */ u32 mode = pCDS->iExternalAttr >> 16; if( !(mode & S_IFDIR) && pCDS->zFile[pCDS->nFile-1]!='/' ){ sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC); } } } break; } case 6: /* method */ sqlite3_result_int(ctx, pCDS->iCompression); break; default: /* z */ assert( i==7 ); sqlite3_result_int64(ctx, pCsr->iId); break; } return rc; } /* ** Return TRUE if the cursor is at EOF. */ static int zipfileEof(sqlite3_vtab_cursor *cur){ ZipfileCsr *pCsr = (ZipfileCsr*)cur; return pCsr->bEof; } /* ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile ** is guaranteed to be a file-handle open on a zip file. ** ** This function attempts to locate the EOCD record within the zip archive ** and populate *pEOCD with the results of decoding it. SQLITE_OK is ** returned if successful. Otherwise, an SQLite error code is returned and ** an English language error message may be left in virtual-table pTab. */ static int zipfileReadEOCD( ZipfileTab *pTab, /* Return errors here */ const u8 *aBlob, /* Pointer to in-memory file image */ int nBlob, /* Size of aBlob[] in bytes */ FILE *pFile, /* Read from this file if aBlob==0 */ ZipfileEOCD *pEOCD /* Object to populate */ ){ u8 *aRead = pTab->aBuffer; /* Temporary buffer */ int nRead; /* Bytes to read from file */ int rc = SQLITE_OK; if( aBlob==0 ){ i64 iOff; /* Offset to read from */ i64 szFile; /* Total size of file in bytes */ fseek(pFile, 0, SEEK_END); szFile = (i64)ftell(pFile); if( szFile==0 ){ memset(pEOCD, 0, sizeof(ZipfileEOCD)); return SQLITE_OK; } nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE)); iOff = szFile - nRead; rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg); }else{ nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE)); aRead = (u8*)&aBlob[nBlob-nRead]; } if( rc==SQLITE_OK ){ int i; /* Scan backwards looking for the signature bytes */ for(i=nRead-20; i>=0; i--){ if( aRead[i]==0x50 && aRead[i+1]==0x4b && aRead[i+2]==0x05 && aRead[i+3]==0x06 ){ break; } } if( i<0 ){ pTab->base.zErrMsg = sqlite3_mprintf( "cannot find end of central directory record" ); return SQLITE_ERROR; } aRead += i+4; pEOCD->iDisk = zipfileRead16(aRead); pEOCD->iFirstDisk = zipfileRead16(aRead); pEOCD->nEntry = zipfileRead16(aRead); pEOCD->nEntryTotal = zipfileRead16(aRead); pEOCD->nSize = zipfileRead32(aRead); pEOCD->iOffset = zipfileRead32(aRead); } return rc; } /* ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added ** to the end of the list. Otherwise, it is added to the list immediately ** before pBefore (which is guaranteed to be a part of said list). */ static void zipfileAddEntry( ZipfileTab *pTab, ZipfileEntry *pBefore, ZipfileEntry *pNew ){ assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) ); assert( pNew->pNext==0 ); if( pBefore==0 ){ if( pTab->pFirstEntry==0 ){ pTab->pFirstEntry = pTab->pLastEntry = pNew; }else{ assert( pTab->pLastEntry->pNext==0 ); pTab->pLastEntry->pNext = pNew; pTab->pLastEntry = pNew; } }else{ ZipfileEntry **pp; for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext)); pNew->pNext = pBefore; *pp = pNew; } } static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){ ZipfileEOCD eocd; int rc; int i; i64 iOff; rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd); iOff = eocd.iOffset; for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){ ZipfileEntry *pNew = 0; rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew); if( rc==SQLITE_OK ){ zipfileAddEntry(pTab, 0, pNew); iOff += ZIPFILE_CDS_FIXED_SZ; iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment; } } return rc; } /* ** xFilter callback. */ static int zipfileFilter( sqlite3_vtab_cursor *cur, int idxNum, const char *idxStr, int argc, sqlite3_value **argv ){ ZipfileTab *pTab = (ZipfileTab*)cur->pVtab; ZipfileCsr *pCsr = (ZipfileCsr*)cur; const char *zFile = 0; /* Zip file to scan */ int rc = SQLITE_OK; /* Return Code */ int bInMemory = 0; /* True for an in-memory zipfile */ zipfileResetCursor(pCsr); if( pTab->zFile ){ zFile = pTab->zFile; }else if( idxNum==0 ){ zipfileCursorErr(pCsr, "zipfile() function requires an argument"); return SQLITE_ERROR; }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){ const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]); int nBlob = sqlite3_value_bytes(argv[0]); assert( pTab->pFirstEntry==0 ); rc = zipfileLoadDirectory(pTab, aBlob, nBlob); pCsr->pFreeEntry = pTab->pFirstEntry; pTab->pFirstEntry = pTab->pLastEntry = 0; if( rc!=SQLITE_OK ) return rc; bInMemory = 1; }else{ zFile = (const char*)sqlite3_value_text(argv[0]); } if( 0==pTab->pWriteFd && 0==bInMemory ){ pCsr->pFile = fopen(zFile, "rb"); if( pCsr->pFile==0 ){ zipfileCursorErr(pCsr, "cannot open file: %s", zFile); rc = SQLITE_ERROR; }else{ rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd); if( rc==SQLITE_OK ){ if( pCsr->eocd.nEntry==0 ){ pCsr->bEof = 1; }else{ pCsr->iNextOff = pCsr->eocd.iOffset; rc = zipfileNext(cur); } } } }else{ pCsr->bNoop = 1; pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry; rc = zipfileNext(cur); } return rc; } /* ** xBestIndex callback. */ static int zipfileBestIndex( sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo ){ int i; int idx = -1; int unusable = 0; for(i=0; i<pIdxInfo->nConstraint; i++){ const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i]; if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue; if( pCons->usable==0 ){ unusable = 1; }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){ idx = i; } } if( idx>=0 ){ pIdxInfo->aConstraintUsage[idx].argvIndex = 1; pIdxInfo->aConstraintUsage[idx].omit = 1; pIdxInfo->estimatedCost = 1000.0; pIdxInfo->idxNum = 1; }else if( unusable ){ return SQLITE_CONSTRAINT; } return SQLITE_OK; } static ZipfileEntry *zipfileNewEntry(const char *zPath){ ZipfileEntry *pNew; pNew = sqlite3_malloc(sizeof(ZipfileEntry)); if( pNew ){ memset(pNew, 0, sizeof(ZipfileEntry)); pNew->cds.zFile = sqlite3_mprintf("%s", zPath); if( pNew->cds.zFile==0 ){ sqlite3_free(pNew); pNew = 0; } } return pNew; } static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){ ZipfileCDS *pCds = &pEntry->cds; u8 *a = aBuf; pCds->nExtra = 9; /* Write the LFH itself */ zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH); zipfileWrite16(a, pCds->iVersionExtract); zipfileWrite16(a, pCds->flags); zipfileWrite16(a, pCds->iCompression); zipfileWrite16(a, pCds->mTime); zipfileWrite16(a, pCds->mDate); zipfileWrite32(a, pCds->crc32); zipfileWrite32(a, pCds->szCompressed); zipfileWrite32(a, pCds->szUncompressed); zipfileWrite16(a, (u16)pCds->nFile); zipfileWrite16(a, pCds->nExtra); assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] ); /* Add the file name */ memcpy(a, pCds->zFile, (int)pCds->nFile); a += (int)pCds->nFile; /* The "extra" data */ zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP); zipfileWrite16(a, 5); *a++ = 0x01; zipfileWrite32(a, pEntry->mUnixTime); return a-aBuf; } static int zipfileAppendEntry( ZipfileTab *pTab, ZipfileEntry *pEntry, const u8 *pData, int nData ){ u8 *aBuf = pTab->aBuffer; int nBuf; int rc; nBuf = zipfileSerializeLFH(pEntry, aBuf); rc = zipfileAppendData(pTab, aBuf, nBuf); if( rc==SQLITE_OK ){ pEntry->iDataOff = pTab->szCurrent; rc = zipfileAppendData(pTab, pData, nData); } return rc; } static int zipfileGetMode( sqlite3_value *pVal, int bIsDir, /* If true, default to directory */ u32 *pMode, /* OUT: Mode value */ char **pzErr /* OUT: Error message */ ){ const char *z = (const char*)sqlite3_value_text(pVal); u32 mode = 0; if( z==0 ){ mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644)); }else if( z[0]>='0' && z[0]<='9' ){ mode = (unsigned int)sqlite3_value_int(pVal); }else{ const char zTemplate[11] = "-rwxrwxrwx"; int i; if( strlen(z)!=10 ) goto parse_error; switch( z[0] ){ case '-': mode |= S_IFREG; break; case 'd': mode |= S_IFDIR; break; case 'l': mode |= S_IFLNK; break; default: goto parse_error; } for(i=1; i<10; i++){ if( z[i]==zTemplate[i] ) mode |= 1 << (9-i); else if( z[i]!='-' ) goto parse_error; } } if( ((mode & S_IFDIR)==0)==bIsDir ){ /* The "mode" attribute is a directory, but data has been specified. ** Or vice-versa - no data but "mode" is a file or symlink. */ *pzErr = sqlite3_mprintf("zipfile: mode does not match data"); return SQLITE_CONSTRAINT; } *pMode = mode; return SQLITE_OK; parse_error: *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z); return SQLITE_ERROR; } /* ** Both (const char*) arguments point to nul-terminated strings. Argument ** nB is the value of strlen(zB). This function returns 0 if the strings are ** identical, ignoring any trailing '/' character in either path. */ static int zipfileComparePath(const char *zA, const char *zB, int nB){ int nA = (int)strlen(zA); if( zA[nA-1]=='/' ) nA--; if( zB[nB-1]=='/' ) nB--; if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0; return 1; } static int zipfileBegin(sqlite3_vtab *pVtab){ ZipfileTab *pTab = (ZipfileTab*)pVtab; int rc = SQLITE_OK; assert( pTab->pWriteFd==0 ); /* Open a write fd on the file. Also load the entire central directory ** structure into memory. During the transaction any new file data is ** appended to the archive file, but the central directory is accumulated ** in main-memory until the transaction is committed. */ pTab->pWriteFd = fopen(pTab->zFile, "ab+"); if( pTab->pWriteFd==0 ){ pTab->base.zErrMsg = sqlite3_mprintf( "zipfile: failed to open file %s for writing", pTab->zFile ); rc = SQLITE_ERROR; }else{ fseek(pTab->pWriteFd, 0, SEEK_END); pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd); rc = zipfileLoadDirectory(pTab, 0, 0); } if( rc!=SQLITE_OK ){ zipfileCleanupTransaction(pTab); } return rc; } /* ** Return the current time as a 32-bit timestamp in UNIX epoch format (like ** time(2)). */ static u32 zipfileTime(void){ sqlite3_vfs *pVfs = sqlite3_vfs_find(0); u32 ret; if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){ i64 ms; pVfs->xCurrentTimeInt64(pVfs, &ms); ret = (u32)((ms/1000) - ((i64)24405875 * 8640)); }else{ double day; pVfs->xCurrentTime(pVfs, &day); ret = (u32)((day - 2440587.5) * 86400); } return ret; } /* ** Return a 32-bit timestamp in UNIX epoch format. ** ** If the value passed as the only argument is either NULL or an SQL NULL, ** return the current time. Otherwise, return the value stored in (*pVal) ** cast to a 32-bit unsigned integer. */ static u32 zipfileGetTime(sqlite3_value *pVal){ if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){ return zipfileTime(); } return (u32)sqlite3_value_int64(pVal); } /* ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry ** linked list. Remove it from the list and free the object. */ static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){ if( pOld ){ ZipfileEntry **pp; for(pp=&pTab->pFirstEntry; (*pp)!=pOld; pp=&((*pp)->pNext)); *pp = (*pp)->pNext; zipfileEntryFree(pOld); } } /* ** xUpdate method. */ static int zipfileUpdate( sqlite3_vtab *pVtab, int nVal, sqlite3_value **apVal, sqlite_int64 *pRowid ){ ZipfileTab *pTab = (ZipfileTab*)pVtab; int rc = SQLITE_OK; /* Return Code */ ZipfileEntry *pNew = 0; /* New in-memory CDS entry */ u32 mode = 0; /* Mode for new entry */ u32 mTime = 0; /* Modification time for new entry */ i64 sz = 0; /* Uncompressed size */ const char *zPath = 0; /* Path for new entry */ int nPath = 0; /* strlen(zPath) */ const u8 *pData = 0; /* Pointer to buffer containing content */ int nData = 0; /* Size of pData buffer in bytes */ int iMethod = 0; /* Compression method for new entry */ u8 *pFree = 0; /* Free this */ char *zFree = 0; /* Also free this */ ZipfileEntry *pOld = 0; ZipfileEntry *pOld2 = 0; int bUpdate = 0; /* True for an update that modifies "name" */ int bIsDir = 0; u32 iCrc32 = 0; if( pTab->pWriteFd==0 ){ rc = zipfileBegin(pVtab); if( rc!=SQLITE_OK ) return rc; } /* If this is a DELETE or UPDATE, find the archive entry to delete. */ if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){ const char *zDelete = (const char*)sqlite3_value_text(apVal[0]); int nDelete = (int)strlen(zDelete); if( nVal>1 ){ const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]); if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){ bUpdate = 1; } } for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){ if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){ break; } assert( pOld->pNext ); } } if( nVal>1 ){ /* Check that "sz" and "rawdata" are both NULL: */ if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){ zipfileTableErr(pTab, "sz must be NULL"); rc = SQLITE_CONSTRAINT; } if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){ zipfileTableErr(pTab, "rawdata must be NULL"); rc = SQLITE_CONSTRAINT; } if( rc==SQLITE_OK ){ if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){ /* data=NULL. A directory */ bIsDir = 1; }else{ /* Value specified for "data", and possibly "method". This must be ** a regular file or a symlink. */ const u8 *aIn = sqlite3_value_blob(apVal[7]); int nIn = sqlite3_value_bytes(apVal[7]); int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL; iMethod = sqlite3_value_int(apVal[8]); sz = nIn; pData = aIn; nData = nIn; if( iMethod!=0 && iMethod!=8 ){ zipfileTableErr(pTab, "unknown compression method: %d", iMethod); rc = SQLITE_CONSTRAINT; }else{ if( bAuto || iMethod ){ int nCmp; rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg); if( rc==SQLITE_OK ){ if( iMethod || nCmp<nIn ){ iMethod = 8; pData = pFree; nData = nCmp; } } } iCrc32 = crc32(0, aIn, nIn); } } } if( rc==SQLITE_OK ){ rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg); } if( rc==SQLITE_OK ){ zPath = (const char*)sqlite3_value_text(apVal[2]); nPath = (int)strlen(zPath); mTime = zipfileGetTime(apVal[4]); } if( rc==SQLITE_OK && bIsDir ){ /* For a directory, check that the last character in the path is a ** '/'. This appears to be required for compatibility with info-zip ** (the unzip command on unix). It does not create directories ** otherwise. */ if( zPath[nPath-1]!='/' ){ zFree = sqlite3_mprintf("%s/", zPath); if( zFree==0 ){ rc = SQLITE_NOMEM; } zPath = (const char*)zFree; nPath++; } } /* Check that we're not inserting a duplicate entry -OR- updating an ** entry with a path, thereby making it into a duplicate. */ if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){ ZipfileEntry *p; for(p=pTab->pFirstEntry; p; p=p->pNext){ if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){ switch( sqlite3_vtab_on_conflict(pTab->db) ){ case SQLITE_IGNORE: { goto zipfile_update_done; } case SQLITE_REPLACE: { pOld2 = p; break; } default: { zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath); rc = SQLITE_CONSTRAINT; break; } } break; } } } if( rc==SQLITE_OK ){ /* Create the new CDS record. */ pNew = zipfileNewEntry(zPath); if( pNew==0 ){ rc = SQLITE_NOMEM; }else{ pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY; pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED; pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS; pNew->cds.iCompression = (u16)iMethod; zipfileMtimeToDos(&pNew->cds, mTime); pNew->cds.crc32 = iCrc32; pNew->cds.szCompressed = nData; pNew->cds.szUncompressed = (u32)sz; pNew->cds.iExternalAttr = (mode<<16); pNew->cds.iOffset = (u32)pTab->szCurrent; pNew->cds.nFile = (u16)nPath; pNew->mUnixTime = (u32)mTime; rc = zipfileAppendEntry(pTab, pNew, pData, nData); zipfileAddEntry(pTab, pOld, pNew); } } } if( rc==SQLITE_OK && (pOld || pOld2) ){ ZipfileCsr *pCsr; for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){ if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){ pCsr->pCurrent = pCsr->pCurrent->pNext; pCsr->bNoop = 1; } } zipfileRemoveEntryFromList(pTab, pOld); zipfileRemoveEntryFromList(pTab, pOld2); } zipfile_update_done: sqlite3_free(pFree); sqlite3_free(zFree); return rc; } static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){ u8 *a = aBuf; zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD); zipfileWrite16(a, p->iDisk); zipfileWrite16(a, p->iFirstDisk); zipfileWrite16(a, p->nEntry); zipfileWrite16(a, p->nEntryTotal); zipfileWrite32(a, p->nSize); zipfileWrite32(a, p->iOffset); zipfileWrite16(a, 0); /* Size of trailing comment in bytes*/ return a-aBuf; } static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){ int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer); assert( nBuf==ZIPFILE_EOCD_FIXED_SZ ); return zipfileAppendData(pTab, pTab->aBuffer, nBuf); } /* ** Serialize the CDS structure into buffer aBuf[]. Return the number ** of bytes written. */ static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){ u8 *a = aBuf; ZipfileCDS *pCDS = &pEntry->cds; if( pEntry->aExtra==0 ){ pCDS->nExtra = 9; } zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS); zipfileWrite16(a, pCDS->iVersionMadeBy); zipfileWrite16(a, pCDS->iVersionExtract); zipfileWrite16(a, pCDS->flags); zipfileWrite16(a, pCDS->iCompression); zipfileWrite16(a, pCDS->mTime); zipfileWrite16(a, pCDS->mDate); zipfileWrite32(a, pCDS->crc32); zipfileWrite32(a, pCDS->szCompressed); zipfileWrite32(a, pCDS->szUncompressed); assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] ); zipfileWrite16(a, pCDS->nFile); zipfileWrite16(a, pCDS->nExtra); zipfileWrite16(a, pCDS->nComment); zipfileWrite16(a, pCDS->iDiskStart); zipfileWrite16(a, pCDS->iInternalAttr); zipfileWrite32(a, pCDS->iExternalAttr); zipfileWrite32(a, pCDS->iOffset); memcpy(a, pCDS->zFile, pCDS->nFile); a += pCDS->nFile; if( pEntry->aExtra ){ int n = (int)pCDS->nExtra + (int)pCDS->nComment; memcpy(a, pEntry->aExtra, n); a += n; }else{ assert( pCDS->nExtra==9 ); zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP); zipfileWrite16(a, 5); *a++ = 0x01; zipfileWrite32(a, pEntry->mUnixTime); } return a-aBuf; } static int zipfileCommit(sqlite3_vtab *pVtab){ ZipfileTab *pTab = (ZipfileTab*)pVtab; int rc = SQLITE_OK; if( pTab->pWriteFd ){ i64 iOffset = pTab->szCurrent; ZipfileEntry *p; ZipfileEOCD eocd; int nEntry = 0; /* Write out all entries */ for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){ int n = zipfileSerializeCDS(p, pTab->aBuffer); rc = zipfileAppendData(pTab, pTab->aBuffer, n); nEntry++; } /* Write out the EOCD record */ eocd.iDisk = 0; eocd.iFirstDisk = 0; eocd.nEntry = (u16)nEntry; eocd.nEntryTotal = (u16)nEntry; eocd.nSize = (u32)(pTab->szCurrent - iOffset); eocd.iOffset = (u32)iOffset; rc = zipfileAppendEOCD(pTab, &eocd); zipfileCleanupTransaction(pTab); } return rc; } static int zipfileRollback(sqlite3_vtab *pVtab){ return zipfileCommit(pVtab); } static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){ ZipfileCsr *pCsr; for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){ if( iId==pCsr->iId ) break; } return pCsr; } static void zipfileFunctionCds( sqlite3_context *context, int argc, sqlite3_value **argv ){ ZipfileCsr *pCsr; ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context); assert( argc>0 ); pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0])); if( pCsr ){ ZipfileCDS *p = &pCsr->pCurrent->cds; char *zRes = sqlite3_mprintf("{" "\"version-made-by\" : %u, " "\"version-to-extract\" : %u, " "\"flags\" : %u, " "\"compression\" : %u, " "\"time\" : %u, " "\"date\" : %u, " "\"crc32\" : %u, " "\"compressed-size\" : %u, " "\"uncompressed-size\" : %u, " "\"file-name-length\" : %u, " "\"extra-field-length\" : %u, " "\"file-comment-length\" : %u, " "\"disk-number-start\" : %u, " "\"internal-attr\" : %u, " "\"external-attr\" : %u, " "\"offset\" : %u }", (u32)p->iVersionMadeBy, (u32)p->iVersionExtract, (u32)p->flags, (u32)p->iCompression, (u32)p->mTime, (u32)p->mDate, (u32)p->crc32, (u32)p->szCompressed, (u32)p->szUncompressed, (u32)p->nFile, (u32)p->nExtra, (u32)p->nComment, (u32)p->iDiskStart, (u32)p->iInternalAttr, (u32)p->iExternalAttr, (u32)p->iOffset ); if( zRes==0 ){ sqlite3_result_error_nomem(context); }else{ sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT); sqlite3_free(zRes); } } } /* ** xFindFunction method. */ static int zipfileFindFunction( sqlite3_vtab *pVtab, /* Virtual table handle */ int nArg, /* Number of SQL function arguments */ const char *zName, /* Name of SQL function */ void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */ void **ppArg /* OUT: User data for *pxFunc */ ){ if( sqlite3_stricmp("zipfile_cds", zName)==0 ){ *pxFunc = zipfileFunctionCds; *ppArg = (void*)pVtab; return 1; } return 0; } typedef struct ZipfileBuffer ZipfileBuffer; struct ZipfileBuffer { u8 *a; /* Pointer to buffer */ int n; /* Size of buffer in bytes */ int nAlloc; /* Byte allocated at a[] */ }; typedef struct ZipfileCtx ZipfileCtx; struct ZipfileCtx { int nEntry; ZipfileBuffer body; ZipfileBuffer cds; }; static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){ if( pBuf->n+nByte>pBuf->nAlloc ){ u8 *aNew; sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512; int nReq = pBuf->n + nByte; while( nNew<nReq ) nNew = nNew*2; aNew = sqlite3_realloc64(pBuf->a, nNew); if( aNew==0 ) return SQLITE_NOMEM; pBuf->a = aNew; pBuf->nAlloc = (int)nNew; } return SQLITE_OK; } /* ** xStep() callback for the zipfile() aggregate. This can be called in ** any of the following ways: ** ** SELECT zipfile(name,data) ... ** SELECT zipfile(name,mode,mtime,data) ... ** SELECT zipfile(name,mode,mtime,data,method) ... */ void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){ ZipfileCtx *p; /* Aggregate function context */ ZipfileEntry e; /* New entry to add to zip archive */ sqlite3_value *pName = 0; sqlite3_value *pMode = 0; sqlite3_value *pMtime = 0; sqlite3_value *pData = 0; sqlite3_value *pMethod = 0; int bIsDir = 0; u32 mode; int rc = SQLITE_OK; char *zErr = 0; int iMethod = -1; /* Compression method to use (0 or 8) */ const u8 *aData = 0; /* Possibly compressed data for new entry */ int nData = 0; /* Size of aData[] in bytes */ int szUncompressed = 0; /* Size of data before compression */ u8 *aFree = 0; /* Free this before returning */ u32 iCrc32 = 0; /* crc32 of uncompressed data */ char *zName = 0; /* Path (name) of new entry */ int nName = 0; /* Size of zName in bytes */ char *zFree = 0; /* Free this before returning */ int nByte; memset(&e, 0, sizeof(e)); p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx)); if( p==0 ) return; /* Martial the arguments into stack variables */ if( nVal!=2 && nVal!=4 && nVal!=5 ){ zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()"); rc = SQLITE_ERROR; goto zipfile_step_out; } pName = apVal[0]; if( nVal==2 ){ pData = apVal[1]; }else{ pMode = apVal[1]; pMtime = apVal[2]; pData = apVal[3]; if( nVal==5 ){ pMethod = apVal[4]; } } /* Check that the 'name' parameter looks ok. */ zName = (char*)sqlite3_value_text(pName); nName = sqlite3_value_bytes(pName); if( zName==0 ){ zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL"); rc = SQLITE_ERROR; goto zipfile_step_out; } /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use ** deflate compression) or NULL (choose automatically). */ if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){ iMethod = (int)sqlite3_value_int64(pMethod); if( iMethod!=0 && iMethod!=8 ){ zErr = sqlite3_mprintf("illegal method value: %d", iMethod); rc = SQLITE_ERROR; goto zipfile_step_out; } } /* Now inspect the data. If this is NULL, then the new entry must be a ** directory. Otherwise, figure out whether or not the data should ** be deflated or simply stored in the zip archive. */ if( sqlite3_value_type(pData)==SQLITE_NULL ){ bIsDir = 1; iMethod = 0; }else{ aData = sqlite3_value_blob(pData); szUncompressed = nData = sqlite3_value_bytes(pData); iCrc32 = crc32(0, aData, nData); if( iMethod<0 || iMethod==8 ){ int nOut = 0; rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr); if( rc!=SQLITE_OK ){ goto zipfile_step_out; } if( iMethod==8 || nOut<nData ){ aData = aFree; nData = nOut; iMethod = 8; }else{ iMethod = 0; } } } /* Decode the "mode" argument. */ rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr); if( rc ) goto zipfile_step_out; /* Decode the "mtime" argument. */ e.mUnixTime = zipfileGetTime(pMtime); /* If this is a directory entry, ensure that there is exactly one '/' ** at the end of the path. Or, if this is not a directory and the path ** ends in '/' it is an error. */ if( bIsDir==0 ){ if( zName[nName-1]=='/' ){ zErr = sqlite3_mprintf("non-directory name must not end with /"); rc = SQLITE_ERROR; goto zipfile_step_out; } }else{ if( zName[nName-1]!='/' ){ zName = zFree = sqlite3_mprintf("%s/", zName); nName++; if( zName==0 ){ rc = SQLITE_NOMEM; goto zipfile_step_out; } }else{ while( nName>1 && zName[nName-2]=='/' ) nName--; } } /* Assemble the ZipfileEntry object for the new zip archive entry */ e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY; e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED; e.cds.flags = ZIPFILE_NEWENTRY_FLAGS; e.cds.iCompression = (u16)iMethod; zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime); e.cds.crc32 = iCrc32; e.cds.szCompressed = nData; e.cds.szUncompressed = szUncompressed; e.cds.iExternalAttr = (mode<<16); e.cds.iOffset = p->body.n; e.cds.nFile = (u16)nName; e.cds.zFile = zName; /* Append the LFH to the body of the new archive */ nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9; if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out; p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]); /* Append the data to the body of the new archive */ if( nData>0 ){ if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out; memcpy(&p->body.a[p->body.n], aData, nData); p->body.n += nData; } /* Append the CDS record to the directory of the new archive */ nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9; if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out; p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]); /* Increment the count of entries in the archive */ p->nEntry++; zipfile_step_out: sqlite3_free(aFree); sqlite3_free(zFree); if( rc ){ if( zErr ){ sqlite3_result_error(pCtx, zErr, -1); }else{ sqlite3_result_error_code(pCtx, rc); } } sqlite3_free(zErr); } /* ** xFinalize() callback for zipfile aggregate function. */ void zipfileFinal(sqlite3_context *pCtx){ ZipfileCtx *p; ZipfileEOCD eocd; sqlite3_int64 nZip; u8 *aZip; p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx)); if( p==0 ) return; if( p->nEntry>0 ){ memset(&eocd, 0, sizeof(eocd)); eocd.nEntry = (u16)p->nEntry; eocd.nEntryTotal = (u16)p->nEntry; eocd.nSize = p->cds.n; eocd.iOffset = p->body.n; nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ; aZip = (u8*)sqlite3_malloc64(nZip); if( aZip==0 ){ sqlite3_result_error_nomem(pCtx); }else{ memcpy(aZip, p->body.a, p->body.n); memcpy(&aZip[p->body.n], p->cds.a, p->cds.n); zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]); sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree); } } sqlite3_free(p->body.a); sqlite3_free(p->cds.a); } /* ** Register the "zipfile" virtual table. */ static int zipfileRegister(sqlite3 *db){ static sqlite3_module zipfileModule = { 1, /* iVersion */ zipfileConnect, /* xCreate */ zipfileConnect, /* xConnect */ zipfileBestIndex, /* xBestIndex */ zipfileDisconnect, /* xDisconnect */ zipfileDisconnect, /* xDestroy */ zipfileOpen, /* xOpen - open a cursor */ zipfileClose, /* xClose - close a cursor */ zipfileFilter, /* xFilter - configure scan constraints */ zipfileNext, /* xNext - advance a cursor */ zipfileEof, /* xEof - check for end of scan */ zipfileColumn, /* xColumn - read data */ 0, /* xRowid - read data */ zipfileUpdate, /* xUpdate */ zipfileBegin, /* xBegin */ 0, /* xSync */ zipfileCommit, /* xCommit */ zipfileRollback, /* xRollback */ zipfileFindFunction, /* xFindMethod */ 0, /* xRename */ }; int rc = sqlite3_create_module(db, "zipfile" , &zipfileModule, 0); if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1); if( rc==SQLITE_OK ){ rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0, zipfileStep, zipfileFinal ); } return rc; } #else /* SQLITE_OMIT_VIRTUALTABLE */ # define zipfileRegister(x) SQLITE_OK #endif #ifdef _WIN32 __declspec(dllexport) #endif int sqlite3_zipfile_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ SQLITE_EXTENSION_INIT2(pApi); (void)pzErrMsg; /* Unused parameter */ return zipfileRegister(db); }
the_stack_data/57951355.c
#include "stdio.h" extern int test( int a, int b); extern int verification ( int a , int b); int main( int argc, char **argv) { printf("\n\n"); int a=0x00000000; printf("ANDN (0x%08x, 0x%08x) = 0x%08x \n",a,a,test(a,a)); printf("AND (0x%08x,NOT 0x%08x) = 0x%08x \n\n",a,a,verification(a,a)); int b=0x0000000f; printf("ANDN (0x%08x, 0x%08x) = 0x%08x \n",a,b,test(a,b)); printf("AND (0x%08x,NOT 0x%08x) = 0x%08x \n\n",a,b,verification(a,b)); printf("ANDN (0x%08x, 0x%08x) = 0x%08x \n",b,a,test(b,a)); printf("AND (0x%08x,NOT 0x%08x) = 0x%08x \n\n",b,a,verification(b,a)); int c=0x00001111; printf("ANDN (0x%08x, 0x%08x) = 0x%08x \n",a,c,test(a,c)); printf("AND (0x%08x,NOT 0x%08x) = 0x%08x \n\n",a,c,verification(a,c)); printf("ANDN (0x%08x, 0x%08x) = 0x%08x \n",c,a,test(c,a)); printf("AND (0x%08x,NOT 0x%08x) = 0x%08x \n\n",c,a,verification(c,a)); int d=0x00000001; printf("ANDN (0x%08x, 0x%08x) = 0x%08x \n",d,b,test(d,b)); printf("AND (0x%08x,NOT 0x%08x) = 0x%08x \n\n",d,b,verification(d,b)); int e=0x123; printf("ANDN (0x%08x, 0x%08x) = 0x%08x \n",e,a,test(e,a)); printf("AND (0x%08x,NOT 0x%08x) = 0x%08x \n\n",e,a,verification(e,a)); int f=0x12300000; printf("ANDN (0x%08x, 0x%08x) = 0x%08x \n",f,b,test(f,b)); printf("AND (0x%08x,NOT 0x%08x) = 0x%08x \n\n",f,b,verification(f,b)); int g= 0xffffffff; printf("ANDN (0x%08x, 0x%08x) = 0x%08x \n",g,g,test(g,g)); printf("AND (0x%08x,NOT 0x%08x) = 0x%08x \n\n",g,g,verification(g,g)); printf("ANDN (0x%08x, 0x%08x) = 0x%08x \n",a,g,test(a,g)); printf("AND (0x%08x,NOT 0x%08x) = 0x%08x \n\n",a,g,verification(a,g)); printf("ANDN (0x%08x, 0x%08x) = 0x%08x \n",g,a,test(g,a)); printf("AND (0x%08x,NOT 0x%08x) = 0x%08x \n\n",g,a,verification(g,a)); int k=0x11111111; printf("ANDN (0x%08x, 0x%08x) = 0x%08x \n",k,b,test(k,b)); printf("AND (0x%08x,NOT 0x%08x) = 0x%08x \n\n",k,b,verification(k,b)); int s= 0x74B0DC51; int r= 0x19495CFF; printf("ANDN (0x%08x, 0x%08x) = 0x%08x \n",s,r,test(s,r)); printf("AND (0x%08x,NOT 0x%08x) = 0x%08x \n\n ",s,r,verification(s,r)); return 0; }