file
stringlengths
18
26
data
stringlengths
3
1.04M
the_stack_data/105839.c
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #define NUM_THREADS 2 /* create thread argument struct for thr_func() */ typedef struct _thread_data_t { int tid; double stuff; } thread_data_t; /* thread function */ void *thr_func(void *arg) { thread_data_t *data = (thread_data_t *)arg; printf("hello from thr_func, thread id: %d\n", data->tid); pthread_exit(NULL); } int main(int argc, char **argv) { pthread_t thr[NUM_THREADS]; int i, rc; /* create a thread_data_t argument array */ thread_data_t thr_data[NUM_THREADS]; /* create threads */ for (i = 0; i < NUM_THREADS; ++i) { thr_data[i].tid = i; if ((rc = pthread_create(&thr[i], NULL, thr_func, &thr_data[i]))) { fprintf(stderr, "error: pthread_create, rc: %d\n", rc); return EXIT_FAILURE; } } /* block until all threads complete */ for (i = 0; i < NUM_THREADS; ++i) { pthread_join(thr[i], NULL); } return EXIT_SUCCESS; }
the_stack_data/64442.c
#include <stdio.h> #include <stdlib.h> int main(void) { FILE *fp = NULL; static const char example_data[] = "lauf davon, so schnell du kannst"; if (!(fp = tmpfile())) { perror("tmpfile"); exit(1); } const size_t nmemb = sizeof(example_data) - 1; // skip terminating zero if (fwrite(example_data, 1, nmemb, fp) != nmemb) { perror("fwrite"); exit(1); } if (fclose(fp) == EOF) { perror("fclose"); exit(1); } return 0; }
the_stack_data/43304.c
// Exercise 4-1. // Write the function strindex(s,t) which returns the position of the rightmost // occurrence of t in s, or -1 if there is none. #include <stdio.h> int main() { fprintf(stderr, "not yet done\n"); return 1; }
the_stack_data/886525.c
/* Test generation of machhw on 405. */ /* Origin: Joseph Myers <[email protected]> */ /* { dg-do compile } */ /* { dg-require-effective-target ilp32 } */ /* { dg-options "-O2 -mcpu=405" } */ /* { dg-final { scan-assembler "machhw " } } */ int f(int a, int b, int c) { a += (b >> 16) * (c >> 16); return a; }
the_stack_data/795287.c
extern const unsigned char INSPhotoGalleryVersionString[]; extern const double INSPhotoGalleryVersionNumber; const unsigned char INSPhotoGalleryVersionString[] __attribute__ ((used)) = "@(#)PROGRAM:INSPhotoGallery PROJECT:Pods-1" "\n"; const double INSPhotoGalleryVersionNumber __attribute__ ((used)) = (double)1.;
the_stack_data/193894444.c
_Noreturn void f(void){ while (1) {} } int g(void) { return 0; } int main(void){ return g(); }
the_stack_data/155471.c
#include <stdio.h> int main() { int sum, cur, i, M; while (1 == scanf("%d", &M)) { sum = 0; for (i = 0; i < M; i++) { scanf("%d", &cur); sum += cur; } printf("%d\n", sum); } return 0; } /************************************************************** Problem: 1244 User: zj Language: C Result: Accepted Time:0 ms Memory:944 kb ****************************************************************/
the_stack_data/866063.c
#include <stdio.h> main() { int c, counter; counter = 0; while ((c = getchar()) != EOF) { if (c == '\t' || c == ' ' || c == '\n') { ++counter; printf("%d\n", counter); } } }
the_stack_data/140766980.c
//Avtor: Nikola Stoimenov //Januarski ispit 25.01.2017, Termin 3 Grupa 2, Prva zadacha... #include <stdio.h> #define MAX_ELEMENTI 50 //Odreduva dali x e pozitiven ili negativen int isP(int *x){ if (*(x)>0) return 1; if (*(x)<0) return 0; } int zbir(int *Niza, int kraj){ static int i = 0; static int zb = 0; if(i==0){ if(isP(Niza+i) == 1 && isP(Niza+i+1) == 0) zb += *(Niza+i); if(isP(Niza+i) == 0 && isP(Niza+i+1) == 1) zb += *(Niza+i); } else if(i == kraj-1){ if(isP(Niza+i) == 1 && isP(Niza+i-1) == 0) zb += *(Niza+i); if(isP(Niza+i) == 0 && isP(Niza+i-1) == 1) zb += *(Niza+i); } else { if(isP(Niza+i) && (isP(Niza+i-1) == 0 && isP(Niza+i+1) == 0)) zb += *(Niza+i); if(isP(Niza+i) == 0 && (isP(Niza+i-1) && isP(Niza+i+1) )) zb += *(Niza+i); } i++; if (i < kraj) { zbir(Niza, kraj); return zb; } } int main(){ int niza[] = {7, -2, 2, 1, -5, 6, -2, 2}; printf("%d", zbir(niza, 8)); }
the_stack_data/1005093.c
void gds_bogus_function_for_coverity_model(void) { __coverity_panic__(); }
the_stack_data/72012193.c
#include <stdio.h> int main() { printf("Hello World from t1 Main!\n"); return 0; }
the_stack_data/3263884.c
/* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2021 Gavin D. Howard and contributors. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ***************************************************************************** * * The parser for bc. * */ #if BC_ENABLED #include <assert.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <setjmp.h> #include <bc.h> #include <num.h> #include <vm.h> // Before you embark on trying to understand this code, have you read the // Development manual (manuals/development.md) and the comment in include/bc.h // yet? No? Do that first. I'm serious. // // The reason is because this file holds the most sensitive and finicky code in // the entire codebase. Even getting history to work on Windows was nothing // compared to this. This is where dreams go to die, where dragons live, and // from which Ken Thompson himself would flee. static void bc_parse_else(BcParse *p); static void bc_parse_stmt(BcParse *p); static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, BcParseNext next); static void bc_parse_expr_status(BcParse *p, uint8_t flags, BcParseNext next); /** * Returns true if an instruction could only have come from a "leaf" expression. * For more on what leaf expressions are, read the comment for BC_PARSE_LEAF(). * @param t The instruction to test. */ static bool bc_parse_inst_isLeaf(BcInst t) { return (t >= BC_INST_NUM && t <= BC_INST_MAXSCALE) || #if BC_ENABLE_EXTRA_MATH t == BC_INST_TRUNC || #endif // BC_ENABLE_EXTRA_MATH t <= BC_INST_DEC; } /** * Returns true if the *previous* token was a delimiter. A delimiter is anything * that can legally end a statement. In bc's case, it could be a newline, a * semicolon, and a brace in certain cases. * @param p The parser. * @return True if the token is a legal delimiter. */ static bool bc_parse_isDelimiter(const BcParse *p) { BcLexType t = p->l.t; bool good; // If it's an obvious delimiter, say so. if (BC_PARSE_DELIMITER(t)) return true; good = false; // If the current token is a keyword, then...beware. That means that we need // to check for a "dangling" else, where there was no brace-delimited block // on the previous if. if (t == BC_LEX_KW_ELSE) { size_t i; uint16_t *fptr = NULL, flags = BC_PARSE_FLAG_ELSE; // As long as going up the stack is valid for a dangling else, keep on. for (i = 0; i < p->flags.len && BC_PARSE_BLOCK_STMT(flags); ++i) { fptr = bc_vec_item_rev(&p->flags, i); flags = *fptr; // If we need a brace and don't have one, then we don't have a // delimiter. if ((flags & BC_PARSE_FLAG_BRACE) && p->l.last != BC_LEX_RBRACE) return false; } // Oh, and we had also better have an if statement somewhere. good = ((flags & BC_PARSE_FLAG_IF) != 0); } else if (t == BC_LEX_RBRACE) { size_t i; // Since we have a brace, we need to just check if a brace was needed. for (i = 0; !good && i < p->flags.len; ++i) { uint16_t *fptr = bc_vec_item_rev(&p->flags, i); good = (((*fptr) & BC_PARSE_FLAG_BRACE) != 0); } } return good; } /** * Returns true if we are in top level of a function body. The POSIX grammar * is defined such that anything is allowed after a function body, so we must * use this function to detect that case when ending a function body. * @param p The parser. * @return True if we are in the top level of parsing a function body. */ static bool bc_parse_TopFunc(const BcParse *p) { bool good = p->flags.len == 2; uint16_t val = BC_PARSE_FLAG_BRACE | BC_PARSE_FLAG_FUNC_INNER; val |= BC_PARSE_FLAG_FUNC; return good && BC_PARSE_TOP_FLAG(p) == val; } /** * Sets a previously defined exit label. What are labels? See the bc Parsing * section of the Development manual (manuals/development.md). * @param p The parser. */ static void bc_parse_setLabel(BcParse *p) { BcFunc *func = p->func; BcInstPtr *ip = bc_vec_top(&p->exits); size_t *label; assert(func == bc_vec_item(&p->prog->fns, p->fidx)); // Set the preallocated label to the correct index. label = bc_vec_item(&func->labels, ip->idx); *label = func->code.len; // Now, we don't need the exit label; it is done. bc_vec_pop(&p->exits); } /** * Creates a label and sets it to idx. If this is an exit label, then idx is * actually invalid, but it doesn't matter because it will be fixed by * bc_parse_setLabel() later. * @param p The parser. * @param idx The index of the label. */ static void bc_parse_createLabel(BcParse *p, size_t idx) { bc_vec_push(&p->func->labels, &idx); } /** * Creates a conditional label. Unlike an exit label, this label is set at * creation time because it comes *before* the code that will target it. * @param p The parser. * @param idx The index of the label. */ static void bc_parse_createCondLabel(BcParse *p, size_t idx) { bc_parse_createLabel(p, p->func->code.len); bc_vec_push(&p->conds, &idx); } /* * Creates an exit label to be filled in later by bc_parse_setLabel(). Also, why * create a label to be filled in later? Because exit labels are meant to be * targeted by code that comes *before* the label. Since we have to parse that * code first, and don't know how long it will be, we need to just make sure to * reserve a slot to be filled in later when we know. * * By the way, this uses BcInstPtr because it was convenient. The field idx * holds the index, and the field func holds the loop boolean. * * @param p The parser. * @param idx The index of the label's position. * @param loop True if the exit label is for a loop or not. */ static void bc_parse_createExitLabel(BcParse *p, size_t idx, bool loop) { BcInstPtr ip; assert(p->func == bc_vec_item(&p->prog->fns, p->fidx)); ip.func = loop; ip.idx = idx; ip.len = 0; bc_vec_push(&p->exits, &ip); bc_parse_createLabel(p, SIZE_MAX); } /** * Pops the correct operators off of the operator stack based on the current * operator. This is because of the Shunting-Yard algorithm. Lower prec means * higher precedence. * @param p The parser. * @param type The operator. * @param start The previous start of the operator stack. For more * information, see the bc Parsing section of the Development * manual (manuals/development.md). * @param nexprs A pointer to the current number of expressions that have not * been consumed yet. This is an IN and OUT parameter. */ static void bc_parse_operator(BcParse *p, BcLexType type, size_t start, size_t *nexprs) { BcLexType t; uchar l, r = BC_PARSE_OP_PREC(type); uchar left = BC_PARSE_OP_LEFT(type); // While we haven't hit the stop point yet. while (p->ops.len > start) { // Get the top operator. t = BC_PARSE_TOP_OP(p); // If it's a right paren, we have reached the end of whatever expression // this is no matter what. if (t == BC_LEX_LPAREN) break; // Break for precedence. Precedence operates differently on left and // right associativity, by the way. A left associative operator that // matches the current precedence should take priority, but a right // associative operator should not. l = BC_PARSE_OP_PREC(t); if (l >= r && (l != r || !left)) break; // Do the housekeeping. In particular, make sure to note that one // expression was consumed. (Two were, but another was added.) bc_parse_push(p, BC_PARSE_TOKEN_INST(t)); bc_vec_pop(&p->ops); *nexprs -= !BC_PARSE_OP_PREFIX(t); } bc_vec_push(&p->ops, &type); } /** * Parses a right paren. In the Shunting-Yard algorithm, it needs to be put on * the operator stack. But before that, it needs to consume whatever operators * there are until it hits a left paren. * @param p The parser. * @param nexprs A pointer to the current number of expressions that have not * been consumed yet. This is an IN and OUT parameter. */ static void bc_parse_rightParen(BcParse *p, size_t *nexprs) { BcLexType top; // Consume operators until a left paren. while ((top = BC_PARSE_TOP_OP(p)) != BC_LEX_LPAREN) { bc_parse_push(p, BC_PARSE_TOKEN_INST(top)); bc_vec_pop(&p->ops); *nexprs -= !BC_PARSE_OP_PREFIX(top); } // We need to pop the left paren as well. bc_vec_pop(&p->ops); // Oh, and we also want the next token. bc_lex_next(&p->l); } /** * Parses function arguments. * @param p The parser. * @param flags Flags restricting what kind of expressions the arguments can * be. */ static void bc_parse_args(BcParse *p, uint8_t flags) { bool comma = false; size_t nargs; bc_lex_next(&p->l); // Print and comparison operators not allowed. Well, comparison operators // only for POSIX. But we do allow arrays, and we *must* get a value. flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL); flags |= (BC_PARSE_ARRAY | BC_PARSE_NEEDVAL); // Count the arguments and parse them. for (nargs = 0; p->l.t != BC_LEX_RPAREN; ++nargs) { bc_parse_expr_status(p, flags, bc_parse_next_arg); comma = (p->l.t == BC_LEX_COMMA); if (comma) bc_lex_next(&p->l); } // An ending comma is FAIL. if (BC_ERR(comma)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); // Now do the call with the number of arguments. bc_parse_push(p, BC_INST_CALL); bc_parse_pushIndex(p, nargs); } /** * Parses a function call. * @param p The parser. * @param flags Flags restricting what kind of expressions the arguments can * be. */ static void bc_parse_call(BcParse *p, const char *name, uint8_t flags) { size_t idx; bc_parse_args(p, flags); // We just assert this because bc_parse_args() should // ensure that the next token is what it should be. assert(p->l.t == BC_LEX_RPAREN); // We cannot use bc_program_insertFunc() here // because it will overwrite an existing function. idx = bc_map_index(&p->prog->fn_map, name); // The function does not exist yet. Create a space for it. If the user does // not define it, it's a *runtime* error, not a parse error. if (idx == BC_VEC_INVALID_IDX) { idx = bc_program_insertFunc(p->prog, name); assert(idx != BC_VEC_INVALID_IDX); // Make sure that this pointer was not invalidated. p->func = bc_vec_item(&p->prog->fns, p->fidx); } // The function exists, so set the right function index. else idx = ((BcId*) bc_vec_item(&p->prog->fn_map, idx))->idx; bc_parse_pushIndex(p, idx); // Make sure to get the next token. bc_lex_next(&p->l); } /** * Parses a name/identifier-based expression. It could be a variable, an array * element, an array itself (for function arguments), a function call, etc. * */ static void bc_parse_name(BcParse *p, BcInst *type, bool *can_assign, uint8_t flags) { char *name; BC_SIG_ASSERT_LOCKED; // We want a copy of the name since the lexer might overwrite its copy. name = bc_vm_strdup(p->l.str.v); BC_SETJMP_LOCKED(err); // We need the next token to see if it's just a variable or something more. bc_lex_next(&p->l); // Array element or array. if (p->l.t == BC_LEX_LBRACKET) { bc_lex_next(&p->l); // Array only. This has to be a function parameter. if (p->l.t == BC_LEX_RBRACKET) { // Error if arrays are not allowed. if (BC_ERR(!(flags & BC_PARSE_ARRAY))) bc_parse_err(p, BC_ERR_PARSE_EXPR); *type = BC_INST_ARRAY; *can_assign = false; } else { // If we are here, we have an array element. We need to set the // expression parsing flags. uint8_t flags2 = (flags & ~(BC_PARSE_PRINT | BC_PARSE_REL)) | BC_PARSE_NEEDVAL; bc_parse_expr_status(p, flags2, bc_parse_next_elem); // The next token *must* be a right bracket. if (BC_ERR(p->l.t != BC_LEX_RBRACKET)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); *type = BC_INST_ARRAY_ELEM; *can_assign = true; } // Make sure to get the next token. bc_lex_next(&p->l); // Push the instruction and the name of the identifier. bc_parse_push(p, *type); bc_parse_pushName(p, name, false); } else if (p->l.t == BC_LEX_LPAREN) { // We are parsing a function call; error if not allowed. if (BC_ERR(flags & BC_PARSE_NOCALL)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); *type = BC_INST_CALL; *can_assign = false; bc_parse_call(p, name, flags); } else { // Just a variable. *type = BC_INST_VAR; *can_assign = true; bc_parse_push(p, BC_INST_VAR); bc_parse_pushName(p, name, true); } err: // Need to make sure to unallocate the name. free(name); BC_LONGJMP_CONT; BC_SIG_MAYLOCK; } /** * Parses a builtin function that takes no arguments. This includes read(), * rand(), maxibase(), maxobase(), maxscale(), and maxrand(). * @param p The parser. * @param inst The instruction corresponding to the builtin. */ static void bc_parse_noArgBuiltin(BcParse *p, BcInst inst) { // Must have a left paren. bc_lex_next(&p->l); if (BC_ERR(p->l.t != BC_LEX_LPAREN)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); // Must have a right paren. bc_lex_next(&p->l); if ((p->l.t != BC_LEX_RPAREN)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); bc_parse_push(p, inst); bc_lex_next(&p->l); } /** * Parses a builtin function that takes 1 argument. This includes length(), * sqrt(), abs(), scale(), and irand(). * @param p The parser. * @param type The lex token. * @param flags The expression parsing flags for parsing the argument. * @param prev An out parameter; the previous instruction pointer. */ static void bc_parse_builtin(BcParse *p, BcLexType type, uint8_t flags, BcInst *prev) { // Must have a left paren. bc_lex_next(&p->l); if (BC_ERR(p->l.t != BC_LEX_LPAREN)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); bc_lex_next(&p->l); // Change the flags as needed for parsing the argument. flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL); flags |= BC_PARSE_NEEDVAL; // Since length can take arrays, we need to specially add that flag. if (type == BC_LEX_KW_LENGTH) flags |= BC_PARSE_ARRAY; bc_parse_expr_status(p, flags, bc_parse_next_rel); // Must have a right paren. if (BC_ERR(p->l.t != BC_LEX_RPAREN)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); // Adjust previous based on the token and push it. *prev = type - BC_LEX_KW_LENGTH + BC_INST_LENGTH; bc_parse_push(p, *prev); bc_lex_next(&p->l); } /** * Parses a builtin function that takes 3 arguments. This includes modexp() and * divmod(). */ static void bc_parse_builtin3(BcParse *p, BcLexType type, uint8_t flags, BcInst *prev) { assert(type == BC_LEX_KW_MODEXP || type == BC_LEX_KW_DIVMOD); // Must have a left paren. bc_lex_next(&p->l); if (BC_ERR(p->l.t != BC_LEX_LPAREN)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); bc_lex_next(&p->l); // Change the flags as needed for parsing the argument. flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL); flags |= BC_PARSE_NEEDVAL; bc_parse_expr_status(p, flags, bc_parse_next_builtin); // Must have a comma. if (BC_ERR(p->l.t != BC_LEX_COMMA)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); bc_lex_next(&p->l); bc_parse_expr_status(p, flags, bc_parse_next_builtin); // Must have a comma. if (BC_ERR(p->l.t != BC_LEX_COMMA)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); bc_lex_next(&p->l); // If it is a divmod, parse an array name. Otherwise, just parse another // expression. if (type == BC_LEX_KW_DIVMOD) { // Must have a name. if (BC_ERR(p->l.t != BC_LEX_NAME)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); // This is safe because the next token should not overwrite the name. bc_lex_next(&p->l); // Must have a left bracket. if (BC_ERR(p->l.t != BC_LEX_LBRACKET)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); // This is safe because the next token should not overwrite the name. bc_lex_next(&p->l); // Must have a right bracket. if (BC_ERR(p->l.t != BC_LEX_RBRACKET)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); // This is safe because the next token should not overwrite the name. bc_lex_next(&p->l); } else bc_parse_expr_status(p, flags, bc_parse_next_rel); // Must have a right paren. if (BC_ERR(p->l.t != BC_LEX_RPAREN)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); // Adjust previous based on the token and push it. *prev = type - BC_LEX_KW_MODEXP + BC_INST_MODEXP; bc_parse_push(p, *prev); // If we have divmod, we need to assign the modulus to the array element, so // we need to push the instructions for doing so. if (type == BC_LEX_KW_DIVMOD) { // The zeroth element. bc_parse_push(p, BC_INST_ZERO); bc_parse_push(p, BC_INST_ARRAY_ELEM); // Push the array. bc_parse_pushName(p, p->l.str.v, false); // Swap them and assign. After this, the top item on the stack should // be the quotient. bc_parse_push(p, BC_INST_SWAP); bc_parse_push(p, BC_INST_ASSIGN_NO_VAL); } bc_lex_next(&p->l); } /** * Parses the scale keyword. This is special because scale can be a value or a * builtin function. * @param p The parser. * @param type An out parameter; the instruction for the parse. * @param can_assign An out parameter; whether the expression can be assigned * to. * @param flags The expression parsing flags for parsing a scale() arg. */ static void bc_parse_scale(BcParse *p, BcInst *type, bool *can_assign, uint8_t flags) { bc_lex_next(&p->l); // Without the left paren, it's just the keyword. if (p->l.t != BC_LEX_LPAREN) { // Set, push, and return. *type = BC_INST_SCALE; *can_assign = true; bc_parse_push(p, BC_INST_SCALE); return; } // Handle the scale function. *type = BC_INST_SCALE_FUNC; *can_assign = false; // Once again, adjust the flags. flags &= ~(BC_PARSE_PRINT | BC_PARSE_REL); flags |= BC_PARSE_NEEDVAL; bc_lex_next(&p->l); bc_parse_expr_status(p, flags, bc_parse_next_rel); // Must have a right paren. if (BC_ERR(p->l.t != BC_LEX_RPAREN)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); bc_parse_push(p, BC_INST_SCALE_FUNC); bc_lex_next(&p->l); } /** * Parses and increment or decrement operator. This is a bit complex. * @param p The parser. * @param prev An out parameter; the previous instruction pointer. * @param can_assign An out parameter; whether the expression can be assigned * to. * @param nexs An in/out parameter; the number of expressions in the * parse tree that are not used. * @param flags The expression parsing flags for parsing a scale() arg. */ static void bc_parse_incdec(BcParse *p, BcInst *prev, bool *can_assign, size_t *nexs, uint8_t flags) { BcLexType type; uchar inst; BcInst etype = *prev; BcLexType last = p->l.last; assert(prev != NULL && can_assign != NULL); // If we can't assign to the previous token, then we have an error. if (BC_ERR(last == BC_LEX_OP_INC || last == BC_LEX_OP_DEC || last == BC_LEX_RPAREN)) { bc_parse_err(p, BC_ERR_PARSE_ASSIGN); } // Is the previous instruction for a variable? if (BC_PARSE_INST_VAR(etype)) { // If so, this is a postfix operator. if (!*can_assign) bc_parse_err(p, BC_ERR_PARSE_ASSIGN); // Only postfix uses BC_INST_INC and BC_INST_DEC. *prev = inst = BC_INST_INC + (p->l.t != BC_LEX_OP_INC); bc_parse_push(p, inst); bc_lex_next(&p->l); *can_assign = false; } else { // This is a prefix operator. In that case, we just convert it to // an assignment instruction. *prev = inst = BC_INST_ASSIGN_PLUS + (p->l.t != BC_LEX_OP_INC); bc_lex_next(&p->l); type = p->l.t; // Because we parse the next part of the expression // right here, we need to increment this. *nexs = *nexs + 1; // Is the next token a normal identifier? if (type == BC_LEX_NAME) { // Parse the name. uint8_t flags2 = flags & ~BC_PARSE_ARRAY; bc_parse_name(p, prev, can_assign, flags2 | BC_PARSE_NOCALL); } // Is the next token a global? else if (type >= BC_LEX_KW_LAST && type <= BC_LEX_KW_OBASE) { bc_parse_push(p, type - BC_LEX_KW_LAST + BC_INST_LAST); bc_lex_next(&p->l); } // Is the next token specifically scale, which needs special treatment? else if (BC_NO_ERR(type == BC_LEX_KW_SCALE)) { bc_lex_next(&p->l); // Check that scale() was not used. if (BC_ERR(p->l.t == BC_LEX_LPAREN)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); else bc_parse_push(p, BC_INST_SCALE); } // Now we know we have an error. else bc_parse_err(p, BC_ERR_PARSE_TOKEN); *can_assign = false; bc_parse_push(p, BC_INST_ONE); bc_parse_push(p, inst); } } /** * Parses the minus operator. This needs special treatment because it is either * subtract or negation. * @param p The parser. * @param prev An in/out parameter; the previous instruction. * @param ops_bgn The size of the operator stack. * @param rparen True if the last token was a right paren. * @param binlast True if the last token was a binary operator. * @param nexprs An in/out parameter; the number of unused expressions. */ static void bc_parse_minus(BcParse *p, BcInst *prev, size_t ops_bgn, bool rparen, bool binlast, size_t *nexprs) { BcLexType type; bc_lex_next(&p->l); // Figure out if it's a minus or a negation. type = BC_PARSE_LEAF(*prev, binlast, rparen) ? BC_LEX_OP_MINUS : BC_LEX_NEG; *prev = BC_PARSE_TOKEN_INST(type); // We can just push onto the op stack because this is the largest // precedence operator that gets pushed. Inc/dec does not. if (type != BC_LEX_OP_MINUS) bc_vec_push(&p->ops, &type); else bc_parse_operator(p, type, ops_bgn, nexprs); } /** * Parses a string. * @param p The parser. * @param inst The instruction corresponding to how the string was found and * how it should be printed. */ static void bc_parse_str(BcParse *p, BcInst inst) { bc_parse_addString(p); bc_parse_push(p, inst); bc_lex_next(&p->l); } /** * Parses a print statement. * @param p The parser. */ static void bc_parse_print(BcParse *p, BcLexType type) { BcLexType t; bool comma = false; BcInst inst = type == BC_LEX_KW_STREAM ? BC_INST_PRINT_STREAM : BC_INST_PRINT_POP; bc_lex_next(&p->l); t = p->l.t; // A print or stream statement has to have *something*. if (bc_parse_isDelimiter(p)) bc_parse_err(p, BC_ERR_PARSE_PRINT); do { // If the token is a string, then print it with escapes. // BC_INST_PRINT_POP plays that role for bc. if (t == BC_LEX_STR) bc_parse_str(p, inst); else { // We have an actual number; parse and add a print instruction. bc_parse_expr_status(p, BC_PARSE_NEEDVAL, bc_parse_next_print); bc_parse_push(p, inst); } // Is the next token a comma? comma = (p->l.t == BC_LEX_COMMA); // Get the next token if we have a comma. if (comma) bc_lex_next(&p->l); else { // If we don't have a comma, the statement needs to end. if (!bc_parse_isDelimiter(p)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); else break; } t = p->l.t; } while (true); // If we have a comma but no token, that's bad. if (BC_ERR(comma)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); } /** * Parses a return statement. * @param p The parser. */ static void bc_parse_return(BcParse *p) { BcLexType t; bool paren; uchar inst = BC_INST_RET0; // If we are not in a function, that's an error. if (BC_ERR(!BC_PARSE_FUNC(p))) bc_parse_err(p, BC_ERR_PARSE_TOKEN); // If we are in a void function, make sure to return void. if (p->func->voidfn) inst = BC_INST_RET_VOID; bc_lex_next(&p->l); t = p->l.t; paren = (t == BC_LEX_LPAREN); // An empty return statement just needs to push the selected instruction. if (bc_parse_isDelimiter(p)) bc_parse_push(p, inst); else { BcParseStatus s; // Need to parse the expression whose value will be returned. s = bc_parse_expr_err(p, BC_PARSE_NEEDVAL, bc_parse_next_expr); // If the expression was empty, just push the selected instruction. if (s == BC_PARSE_STATUS_EMPTY_EXPR) { bc_parse_push(p, inst); bc_lex_next(&p->l); } // POSIX requires parentheses. if (!paren || p->l.last != BC_LEX_RPAREN) { bc_parse_err(p, BC_ERR_POSIX_RET); } // Void functions require an empty expression. if (BC_ERR(p->func->voidfn)) { if (s != BC_PARSE_STATUS_EMPTY_EXPR) bc_parse_verr(p, BC_ERR_PARSE_RET_VOID, p->func->name); } // If we got here, we want to be sure to end the function with a real // return instruction, just in case. else bc_parse_push(p, BC_INST_RET); } } /** * Clears flags that indicate the end of an if statement and its block and sets * the jump location. * @param p The parser. */ static void bc_parse_noElse(BcParse *p) { uint16_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p); *flag_ptr = (*flag_ptr & ~(BC_PARSE_FLAG_IF_END)); bc_parse_setLabel(p); } /** * Ends (finishes parsing) the body of a control statement or a function. * @param p The parser. * @param brace True if the body was ended by a brace, false otherwise. */ static void bc_parse_endBody(BcParse *p, bool brace) { bool has_brace, new_else = false; // We cannot be ending a body if there are no bodies to end. if (BC_ERR(p->flags.len <= 1)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); if (brace) { // The brace was already gotten; make sure that the caller did not lie. // We check for the requirement of braces later. assert(p->l.t == BC_LEX_RBRACE); bc_lex_next(&p->l); // If the next token is not a delimiter, that is a problem. if (BC_ERR(!bc_parse_isDelimiter(p) && !bc_parse_TopFunc(p))) bc_parse_err(p, BC_ERR_PARSE_TOKEN); } // Do we have a brace flag? has_brace = (BC_PARSE_BRACE(p) != 0); do { size_t len = p->flags.len; bool loop; // If we have a brace flag but not a brace, that's a problem. if (has_brace && !brace) bc_parse_err(p, BC_ERR_PARSE_TOKEN); // Are we inside a loop? loop = (BC_PARSE_LOOP_INNER(p) != 0); // If we are ending a loop or an else... if (loop || BC_PARSE_ELSE(p)) { // Loops have condition labels that we have to take care of as well. if (loop) { size_t *label = bc_vec_top(&p->conds); bc_parse_push(p, BC_INST_JUMP); bc_parse_pushIndex(p, *label); bc_vec_pop(&p->conds); } bc_parse_setLabel(p); bc_vec_pop(&p->flags); } // If we are ending a function... else if (BC_PARSE_FUNC_INNER(p)) { BcInst inst = (p->func->voidfn ? BC_INST_RET_VOID : BC_INST_RET0); bc_parse_push(p, inst); bc_parse_updateFunc(p, BC_PROG_MAIN); bc_vec_pop(&p->flags); } // If we have a brace flag and not an if statement, we can pop the top // of the flags stack because they have been taken care of above. else if (has_brace && !BC_PARSE_IF(p)) bc_vec_pop(&p->flags); // This needs to be last to parse nested if's properly. if (BC_PARSE_IF(p) && (len == p->flags.len || !BC_PARSE_BRACE(p))) { // Eat newlines. while (p->l.t == BC_LEX_NLINE) bc_lex_next(&p->l); // *Now* we can pop the flags. bc_vec_pop(&p->flags); // If we are allowed non-POSIX stuff... if (!BC_S) { // Have we found yet another dangling else? *(BC_PARSE_TOP_FLAG_PTR(p)) |= BC_PARSE_FLAG_IF_END; new_else = (p->l.t == BC_LEX_KW_ELSE); // Parse the else or end the if statement body. if (new_else) bc_parse_else(p); else if (!has_brace && (!BC_PARSE_IF_END(p) || brace)) bc_parse_noElse(p); } // POSIX requires us to do the bare minimum only. else bc_parse_noElse(p); } // If these are both true, we have "used" the braces that we found. if (brace && has_brace) brace = false; // This condition was perhaps the hardest single part of the parser. If the // flags stack does not have enough, we should stop. If we have a new else // statement, we should stop. If we do have the end of an if statement and // we have eaten the brace, we should stop. If we do have a brace flag, we // should stop. } while (p->flags.len > 1 && !new_else && (!BC_PARSE_IF_END(p) || brace) && !(has_brace = (BC_PARSE_BRACE(p) != 0))); // If we have a brace, yet no body for it, that's a problem. if (BC_ERR(p->flags.len == 1 && brace)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); else if (brace && BC_PARSE_BRACE(p)) { // If we make it here, we have a brace and a flag for it. uint16_t flags = BC_PARSE_TOP_FLAG(p); // This condition ensure that the *last* body is correctly finished by // popping its flags. if (!(flags & (BC_PARSE_FLAG_FUNC_INNER | BC_PARSE_FLAG_LOOP_INNER)) && !(flags & (BC_PARSE_FLAG_IF | BC_PARSE_FLAG_ELSE)) && !(flags & (BC_PARSE_FLAG_IF_END))) { bc_vec_pop(&p->flags); } } } /** * Starts the body of a control statement or function. * @param p The parser. * @param flags The current flags (will be edited). */ static void bc_parse_startBody(BcParse *p, uint16_t flags) { assert(flags); flags |= (BC_PARSE_TOP_FLAG(p) & (BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_LOOP)); flags |= BC_PARSE_FLAG_BODY; bc_vec_push(&p->flags, &flags); } void bc_parse_endif(BcParse *p) { size_t i; bool good; // Not a problem if this is true. if (BC_NO_ERR(!BC_PARSE_NO_EXEC(p))) return; good = true; // Find an instance of a body that needs closing, i.e., a statement that did // not have a right brace when it should have. for (i = 0; good && i < p->flags.len; ++i) { uint16_t flag = *((uint16_t*) bc_vec_item(&p->flags, i)); good = ((flag & BC_PARSE_FLAG_BRACE) != BC_PARSE_FLAG_BRACE); } // If we did not find such an instance... if (good) { // We set this to restore it later. We don't want the parser thinking // that we are on stdin for this one because it will want more. bool is_stdin = vm.is_stdin; vm.is_stdin = false; // End all of the if statements and loops. while (p->flags.len > 1 || BC_PARSE_IF_END(p)) { if (BC_PARSE_IF_END(p)) bc_parse_noElse(p); if (p->flags.len > 1) bc_parse_endBody(p, false); } vm.is_stdin = is_stdin; } // If we reach here, a block was not properly closed, and we should error. else bc_parse_err(&vm.prs, BC_ERR_PARSE_BLOCK); } /** * Parses an if statement. * @param p The parser. */ static void bc_parse_if(BcParse *p) { // We are allowed relational operators, and we must have a value. size_t idx; uint8_t flags = (BC_PARSE_REL | BC_PARSE_NEEDVAL); // Get the left paren and barf if necessary. bc_lex_next(&p->l); if (BC_ERR(p->l.t != BC_LEX_LPAREN)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); // Parse the condition. bc_lex_next(&p->l); bc_parse_expr_status(p, flags, bc_parse_next_rel); // Must have a right paren. if (BC_ERR(p->l.t != BC_LEX_RPAREN)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); bc_lex_next(&p->l); // Insert the conditional jump instruction. bc_parse_push(p, BC_INST_JUMP_ZERO); idx = p->func->labels.len; // Push the index for the instruction and create an exit label for an else // statement. bc_parse_pushIndex(p, idx); bc_parse_createExitLabel(p, idx, false); bc_parse_startBody(p, BC_PARSE_FLAG_IF); } /** * Parses an else statement. * @param p The parser. */ static void bc_parse_else(BcParse *p) { size_t idx = p->func->labels.len; // We must be at the end of an if statement. if (BC_ERR(!BC_PARSE_IF_END(p))) bc_parse_err(p, BC_ERR_PARSE_TOKEN); // Push an unconditional jump to make bc jump over the else statement if it // executed the original if statement. bc_parse_push(p, BC_INST_JUMP); bc_parse_pushIndex(p, idx); // Clear the else stuff. Yes, that function is misnamed for its use here, // but deal with it. bc_parse_noElse(p); // Create the exit label and parse the body. bc_parse_createExitLabel(p, idx, false); bc_parse_startBody(p, BC_PARSE_FLAG_ELSE); bc_lex_next(&p->l); } /** * Parse a while loop. * @param p The parser. */ static void bc_parse_while(BcParse *p) { // We are allowed relational operators, and we must have a value. size_t idx; uint8_t flags = (BC_PARSE_REL | BC_PARSE_NEEDVAL); // Get the left paren and barf if necessary. bc_lex_next(&p->l); if (BC_ERR(p->l.t != BC_LEX_LPAREN)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); bc_lex_next(&p->l); // Create the labels. Loops need both. bc_parse_createCondLabel(p, p->func->labels.len); idx = p->func->labels.len; bc_parse_createExitLabel(p, idx, true); // Parse the actual condition and barf on non-right paren. bc_parse_expr_status(p, flags, bc_parse_next_rel); if (BC_ERR(p->l.t != BC_LEX_RPAREN)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); bc_lex_next(&p->l); // Now we can push the conditional jump and start the body. bc_parse_push(p, BC_INST_JUMP_ZERO); bc_parse_pushIndex(p, idx); bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER); } /** * Parse a for loop. * @param p The parser. */ static void bc_parse_for(BcParse *p) { size_t cond_idx, exit_idx, body_idx, update_idx; // Barf on the missing left paren. bc_lex_next(&p->l); if (BC_ERR(p->l.t != BC_LEX_LPAREN)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); bc_lex_next(&p->l); // The first statement can be empty, but if it is, check for error in POSIX // mode. Otherwise, parse it. if (p->l.t != BC_LEX_SCOLON) bc_parse_expr_status(p, 0, bc_parse_next_for); else bc_parse_err(p, BC_ERR_POSIX_FOR); // Must have a semicolon. if (BC_ERR(p->l.t != BC_LEX_SCOLON)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); bc_lex_next(&p->l); // These are indices for labels. There are so many of them because the end // of the loop must unconditionally jump to the update code. Then the update // code must unconditionally jump to the condition code. Then the condition // code must *conditionally* jump to the exit. cond_idx = p->func->labels.len; update_idx = cond_idx + 1; body_idx = update_idx + 1; exit_idx = body_idx + 1; // This creates the condition label. bc_parse_createLabel(p, p->func->code.len); // Parse an expression if it exists. if (p->l.t != BC_LEX_SCOLON) { uint8_t flags = (BC_PARSE_REL | BC_PARSE_NEEDVAL); bc_parse_expr_status(p, flags, bc_parse_next_for); } else { // Set this for the next call to bc_parse_number because an empty // condition means that it is an infinite loop, so the condition must be // non-zero. This is safe to set because the current token is a // semicolon, which has no string requirement. bc_vec_string(&p->l.str, sizeof(bc_parse_one) - 1, bc_parse_one); bc_parse_number(p); // An empty condition makes POSIX mad. bc_parse_err(p, BC_ERR_POSIX_FOR); } // Must have a semicolon. if (BC_ERR(p->l.t != BC_LEX_SCOLON)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); bc_lex_next(&p->l); // Now we can set up the conditional jump to the exit and an unconditional // jump to the body right after. The unconditional jump to the body is // because there is update code coming right after the condition, so we need // to skip it to get to the body. bc_parse_push(p, BC_INST_JUMP_ZERO); bc_parse_pushIndex(p, exit_idx); bc_parse_push(p, BC_INST_JUMP); bc_parse_pushIndex(p, body_idx); // Now create the label for the update code. bc_parse_createCondLabel(p, update_idx); // Parse if not empty, and if it is, let POSIX yell if necessary. if (p->l.t != BC_LEX_RPAREN) bc_parse_expr_status(p, 0, bc_parse_next_rel); else bc_parse_err(p, BC_ERR_POSIX_FOR); // Must have a right paren. if (BC_ERR(p->l.t != BC_LEX_RPAREN)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); // Set up a jump to the condition right after the update code. bc_parse_push(p, BC_INST_JUMP); bc_parse_pushIndex(p, cond_idx); bc_parse_createLabel(p, p->func->code.len); // Create an exit label for the body and start the body. bc_parse_createExitLabel(p, exit_idx, true); bc_lex_next(&p->l); bc_parse_startBody(p, BC_PARSE_FLAG_LOOP | BC_PARSE_FLAG_LOOP_INNER); } /** * Parse a statement or token that indicates a loop exit. This includes an * actual loop exit, the break keyword, or the continue keyword. * @param p The parser. * @param type The type of exit. */ static void bc_parse_loopExit(BcParse *p, BcLexType type) { size_t i; BcInstPtr *ip; // Must have a loop. If we don't, that's an error. if (BC_ERR(!BC_PARSE_LOOP(p))) bc_parse_err(p, BC_ERR_PARSE_TOKEN); // If we have a break statement... if (type == BC_LEX_KW_BREAK) { // If there are no exits, something went wrong somewhere. if (BC_ERR(!p->exits.len)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); // Get the exit. i = p->exits.len - 1; ip = bc_vec_item(&p->exits, i); // The condition !ip->func is true if the exit is not for a loop, so we // need to find the first actual loop exit. while (!ip->func && i < p->exits.len) ip = bc_vec_item(&p->exits, i--); // Make sure everything is hunky dory. assert(ip != NULL && (i < p->exits.len || ip->func)); // Set the index for the exit. i = ip->idx; } // If we have a continue statement or just the loop end, jump to the // condition (or update for a foor loop). else i = *((size_t*) bc_vec_top(&p->conds)); // Add the unconditional jump. bc_parse_push(p, BC_INST_JUMP); bc_parse_pushIndex(p, i); bc_lex_next(&p->l); } /** * Parse a function (header). * @param p The parser. */ static void bc_parse_func(BcParse *p) { bool comma = false, voidfn; uint16_t flags; size_t idx; bc_lex_next(&p->l); // Must have a name. if (BC_ERR(p->l.t != BC_LEX_NAME)) bc_parse_err(p, BC_ERR_PARSE_FUNC); // If the name is "void", and POSIX is not on, mark as void. voidfn = (!BC_IS_POSIX && p->l.t == BC_LEX_NAME && !strcmp(p->l.str.v, "void")); // We can safely do this because the expected token should not overwrite the // function name. bc_lex_next(&p->l); // If we *don't* have another name, then void is the name of the function. voidfn = (voidfn && p->l.t == BC_LEX_NAME); // With a void function, allow POSIX to complain and get a new token. if (voidfn) { bc_parse_err(p, BC_ERR_POSIX_VOID); // We can safely do this because the expected token should not overwrite // the function name. bc_lex_next(&p->l); } // Must have a left paren. if (BC_ERR(p->l.t != BC_LEX_LPAREN)) bc_parse_err(p, BC_ERR_PARSE_FUNC); // Make sure the functions map and vector are synchronized. assert(p->prog->fns.len == p->prog->fn_map.len); // Insert the function by name into the map and vector. idx = bc_program_insertFunc(p->prog, p->l.str.v); // Make sure the insert worked. assert(idx); // Update the function pointer and stuff in the parser and set its void. bc_parse_updateFunc(p, idx); p->func->voidfn = voidfn; bc_lex_next(&p->l); // While we do not have a right paren, we are still parsing arguments. while (p->l.t != BC_LEX_RPAREN) { BcType t = BC_TYPE_VAR; // If we have an asterisk, we are parsing a reference argument. if (p->l.t == BC_LEX_OP_MULTIPLY) { t = BC_TYPE_REF; bc_lex_next(&p->l); // Let POSIX complain if necessary. bc_parse_err(p, BC_ERR_POSIX_REF); } // If we don't have a name, the argument will not have a name. Barf. if (BC_ERR(p->l.t != BC_LEX_NAME)) bc_parse_err(p, BC_ERR_PARSE_FUNC); // Increment the number of parameters. p->func->nparams += 1; // Copy the string in the lexer so that we can use the lexer again. bc_vec_string(&p->buf, p->l.str.len, p->l.str.v); bc_lex_next(&p->l); // We are parsing an array parameter if this is true. if (p->l.t == BC_LEX_LBRACKET) { // Set the array type, unless we are already parsing a reference. if (t == BC_TYPE_VAR) t = BC_TYPE_ARRAY; bc_lex_next(&p->l); // The brackets *must* be empty. if (BC_ERR(p->l.t != BC_LEX_RBRACKET)) bc_parse_err(p, BC_ERR_PARSE_FUNC); bc_lex_next(&p->l); } // If we did *not* get a bracket, but we are expecting a reference, we // have a problem. else if (BC_ERR(t == BC_TYPE_REF)) bc_parse_verr(p, BC_ERR_PARSE_REF_VAR, p->buf.v); // Test for comma and get the next token if it exists. comma = (p->l.t == BC_LEX_COMMA); if (comma) bc_lex_next(&p->l); // Insert the parameter into the function. bc_func_insert(p->func, p->prog, p->buf.v, t, p->l.line); } // If we have a comma, but no parameter, barf. if (BC_ERR(comma)) bc_parse_err(p, BC_ERR_PARSE_FUNC); // Start the body. flags = BC_PARSE_FLAG_FUNC | BC_PARSE_FLAG_FUNC_INNER; bc_parse_startBody(p, flags); bc_lex_next(&p->l); // POSIX requires that a brace be on the same line as the function header. // If we don't have a brace, let POSIX throw an error. if (p->l.t != BC_LEX_LBRACE) bc_parse_err(p, BC_ERR_POSIX_BRACE); } /** * Parse an auto list. * @param p The parser. */ static void bc_parse_auto(BcParse *p) { bool comma, one; // Error if the auto keyword appeared in the wrong place. if (BC_ERR(!p->auto_part)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); bc_lex_next(&p->l); p->auto_part = comma = false; // We need at least one variable or array. one = (p->l.t == BC_LEX_NAME); // While we have a variable or array. while (p->l.t == BC_LEX_NAME) { BcType t; // Copy the name from the lexer, so we can use it again. bc_vec_string(&p->buf, p->l.str.len - 1, p->l.str.v); bc_lex_next(&p->l); // If we are parsing an array... if (p->l.t == BC_LEX_LBRACKET) { t = BC_TYPE_ARRAY; bc_lex_next(&p->l); // The brackets *must* be empty. if (BC_ERR(p->l.t != BC_LEX_RBRACKET)) bc_parse_err(p, BC_ERR_PARSE_FUNC); bc_lex_next(&p->l); } else t = BC_TYPE_VAR; // Test for comma and get the next token if it exists. comma = (p->l.t == BC_LEX_COMMA); if (comma) bc_lex_next(&p->l); // Insert the auto into the function. bc_func_insert(p->func, p->prog, p->buf.v, t, p->l.line); } // If we have a comma, but no auto, barf. if (BC_ERR(comma)) bc_parse_err(p, BC_ERR_PARSE_FUNC); // If we don't have any variables or arrays, barf. if (BC_ERR(!one)) bc_parse_err(p, BC_ERR_PARSE_NO_AUTO); // The auto statement should be all that's in the statement. if (BC_ERR(!bc_parse_isDelimiter(p))) bc_parse_err(p, BC_ERR_PARSE_TOKEN); } /** * Parses a body. * @param p The parser. * @param brace True if a brace was encountered, false otherwise. */ static void bc_parse_body(BcParse *p, bool brace) { uint16_t *flag_ptr = BC_PARSE_TOP_FLAG_PTR(p); assert(flag_ptr != NULL); assert(p->flags.len >= 2); // The body flag is for when we expect a body. We got a body, so clear the // flag. *flag_ptr &= ~(BC_PARSE_FLAG_BODY); // If we are inside a function, that means we just barely entered it, and // we can expect an auto list. if (*flag_ptr & BC_PARSE_FLAG_FUNC_INNER) { // We *must* have a brace in this case. if (BC_ERR(!brace)) bc_parse_err(p, BC_ERR_PARSE_TOKEN); p->auto_part = (p->l.t != BC_LEX_KW_AUTO); if (!p->auto_part) { // Make sure this is true to not get a parse error. p->auto_part = true; // Since we already have the auto keyword, parse. bc_parse_auto(p); } // Eat a newline. if (p->l.t == BC_LEX_NLINE) bc_lex_next(&p->l); } else { // This is the easy part. size_t len = p->flags.len; assert(*flag_ptr); // Parse a statement. bc_parse_stmt(p); // This is a very important condition to get right. If there is no // brace, and no body flag, and the flags len hasn't shrunk, then we // have a body that was not delimited by braces, so we need to end it // now, after just one statement. if (!brace && !BC_PARSE_BODY(p) && len <= p->flags.len) bc_parse_endBody(p, false); } } /** * Parses a statement. This is the entry point for just about everything, except * function definitions. * @param p The parser. */ static void bc_parse_stmt(BcParse *p) { size_t len; uint16_t flags; BcLexType type = p->l.t; // Eat newline. if (type == BC_LEX_NLINE) { bc_lex_next(&p->l); return; } // Eat auto list. if (type == BC_LEX_KW_AUTO) { bc_parse_auto(p); return; } // If we reach this point, no auto list is allowed. p->auto_part = false; // Everything but an else needs to be taken care of here, but else is // special. if (type != BC_LEX_KW_ELSE) { // After an if, no else found. if (BC_PARSE_IF_END(p)) { // Clear the expectation for else, end body, and return. Returning // gives us a clean slate for parsing again. bc_parse_noElse(p); if (p->flags.len > 1 && !BC_PARSE_BRACE(p)) bc_parse_endBody(p, false); return; } // With a left brace, we are parsing a body. else if (type == BC_LEX_LBRACE) { // We need to start a body if we are not expecting one yet. if (!BC_PARSE_BODY(p)) { bc_parse_startBody(p, BC_PARSE_FLAG_BRACE); bc_lex_next(&p->l); } // If we *are* expecting a body, that body should get a brace. This // takes care of braces being on a different line than if and loop // headers. else { *(BC_PARSE_TOP_FLAG_PTR(p)) |= BC_PARSE_FLAG_BRACE; bc_lex_next(&p->l); bc_parse_body(p, true); } // If we have reached this point, we need to return for a clean // slate. return; } // This happens when we are expecting a body and get a single statement, // i.e., a body with no braces surrounding it. Returns after for a clean // slate. else if (BC_PARSE_BODY(p) && !BC_PARSE_BRACE(p)) { bc_parse_body(p, false); return; } } len = p->flags.len; flags = BC_PARSE_TOP_FLAG(p); switch (type) { // All of these are valid for expressions. case BC_LEX_OP_INC: case BC_LEX_OP_DEC: case BC_LEX_OP_MINUS: case BC_LEX_OP_BOOL_NOT: case BC_LEX_LPAREN: case BC_LEX_NAME: case BC_LEX_NUMBER: case BC_LEX_KW_IBASE: case BC_LEX_KW_LAST: case BC_LEX_KW_LENGTH: case BC_LEX_KW_OBASE: case BC_LEX_KW_SCALE: #if BC_ENABLE_EXTRA_MATH case BC_LEX_KW_SEED: #endif // BC_ENABLE_EXTRA_MATH case BC_LEX_KW_SQRT: case BC_LEX_KW_ABS: #if BC_ENABLE_EXTRA_MATH case BC_LEX_KW_IRAND: #endif // BC_ENABLE_EXTRA_MATH case BC_LEX_KW_ASCIIFY: case BC_LEX_KW_MODEXP: case BC_LEX_KW_DIVMOD: case BC_LEX_KW_READ: #if BC_ENABLE_EXTRA_MATH case BC_LEX_KW_RAND: #endif // BC_ENABLE_EXTRA_MATH case BC_LEX_KW_MAXIBASE: case BC_LEX_KW_MAXOBASE: case BC_LEX_KW_MAXSCALE: #if BC_ENABLE_EXTRA_MATH case BC_LEX_KW_MAXRAND: #endif // BC_ENABLE_EXTRA_MATH case BC_LEX_KW_LINE_LENGTH: case BC_LEX_KW_GLOBAL_STACKS: case BC_LEX_KW_LEADING_ZERO: { bc_parse_expr_status(p, BC_PARSE_PRINT, bc_parse_next_expr); break; } case BC_LEX_KW_ELSE: { bc_parse_else(p); break; } // Just eat. case BC_LEX_SCOLON: { // Do nothing. break; } case BC_LEX_RBRACE: { bc_parse_endBody(p, true); break; } case BC_LEX_STR: { bc_parse_str(p, BC_INST_PRINT_STR); break; } case BC_LEX_KW_BREAK: case BC_LEX_KW_CONTINUE: { bc_parse_loopExit(p, p->l.t); break; } case BC_LEX_KW_FOR: { bc_parse_for(p); break; } case BC_LEX_KW_HALT: { bc_parse_push(p, BC_INST_HALT); bc_lex_next(&p->l); break; } case BC_LEX_KW_IF: { bc_parse_if(p); break; } case BC_LEX_KW_LIMITS: { // `limits` is a compile-time command, so execute it right away. bc_vm_printf("BC_LONG_BIT = %lu\n", (ulong) BC_LONG_BIT); bc_vm_printf("BC_BASE_DIGS = %lu\n", (ulong) BC_BASE_DIGS); bc_vm_printf("BC_BASE_POW = %lu\n", (ulong) BC_BASE_POW); bc_vm_printf("BC_OVERFLOW_MAX = %lu\n", (ulong) BC_NUM_BIGDIG_MAX); bc_vm_printf("\n"); bc_vm_printf("BC_BASE_MAX = %lu\n", BC_MAX_OBASE); bc_vm_printf("BC_DIM_MAX = %lu\n", BC_MAX_DIM); bc_vm_printf("BC_SCALE_MAX = %lu\n", BC_MAX_SCALE); bc_vm_printf("BC_STRING_MAX = %lu\n", BC_MAX_STRING); bc_vm_printf("BC_NAME_MAX = %lu\n", BC_MAX_NAME); bc_vm_printf("BC_NUM_MAX = %lu\n", BC_MAX_NUM); #if BC_ENABLE_EXTRA_MATH bc_vm_printf("BC_RAND_MAX = %lu\n", BC_MAX_RAND); #endif // BC_ENABLE_EXTRA_MATH bc_vm_printf("MAX Exponent = %lu\n", BC_MAX_EXP); bc_vm_printf("Number of vars = %lu\n", BC_MAX_VARS); bc_lex_next(&p->l); break; } case BC_LEX_KW_STREAM: case BC_LEX_KW_PRINT: { bc_parse_print(p, type); break; } case BC_LEX_KW_QUIT: { // Quit is a compile-time command. We don't exit directly, so the vm // can clean up. vm.status = BC_STATUS_QUIT; BC_JMP; break; } case BC_LEX_KW_RETURN: { bc_parse_return(p); break; } case BC_LEX_KW_WHILE: { bc_parse_while(p); break; } default: { bc_parse_err(p, BC_ERR_PARSE_TOKEN); } } // If the flags did not change, we expect a delimiter. if (len == p->flags.len && flags == BC_PARSE_TOP_FLAG(p)) { if (BC_ERR(!bc_parse_isDelimiter(p))) bc_parse_err(p, BC_ERR_PARSE_TOKEN); } // Make sure semicolons are eaten. while (p->l.t == BC_LEX_SCOLON) bc_lex_next(&p->l); // POSIX's grammar does not allow a function definition after a semicolon // without a newline, so check specifically for that case and error if // the POSIX standard flag is set. if (p->l.last == BC_LEX_SCOLON && p->l.t == BC_LEX_KW_DEFINE && BC_IS_POSIX) { bc_parse_err(p, BC_ERR_POSIX_FUNC_AFTER_SEMICOLON); } } void bc_parse_parse(BcParse *p) { assert(p); BC_SETJMP_LOCKED(exit); // We should not let an EOF get here unless some partial parse was not // completed, in which case, it's the user's fault. if (BC_ERR(p->l.t == BC_LEX_EOF)) bc_parse_err(p, BC_ERR_PARSE_EOF); // Functions need special parsing. else if (p->l.t == BC_LEX_KW_DEFINE) { if (BC_ERR(BC_PARSE_NO_EXEC(p))) { bc_parse_endif(p); if (BC_ERR(BC_PARSE_NO_EXEC(p))) bc_parse_err(p, BC_ERR_PARSE_TOKEN); } bc_parse_func(p); } // Otherwise, parse a normal statement. else bc_parse_stmt(p); exit: // We need to reset on error. if (BC_ERR(((vm.status && vm.status != BC_STATUS_QUIT) || vm.sig))) bc_parse_reset(p); BC_LONGJMP_CONT; BC_SIG_MAYLOCK; } /** * Parse an expression. This is the actual implementation of the Shunting-Yard * Algorithm. * @param p The parser. * @param flags The flags for what is valid in the expression. * @param next A set of tokens for what is valid *after* the expression. * @return A parse status. In some places, an empty expression is an * error, and sometimes, it is required. This allows this function * to tell the caller if the expression was empty and let the * caller handle it. */ static BcParseStatus bc_parse_expr_err(BcParse *p, uint8_t flags, BcParseNext next) { BcInst prev = BC_INST_PRINT; uchar inst = BC_INST_INVALID; BcLexType top, t; size_t nexprs, ops_bgn; uint32_t i, nparens, nrelops; bool pfirst, rprn, done, get_token, assign, bin_last, incdec, can_assign; // One of these *must* be true. assert(!(flags & BC_PARSE_PRINT) || !(flags & BC_PARSE_NEEDVAL)); // These are set very carefully. In fact, controlling the values of these // locals is the biggest part of making this work. ops_bgn especially is // important because it marks where the operator stack begins for *this* // invocation of this function. That's because bc_parse_expr_err() is // recursive (the Shunting-Yard Algorithm is most easily expressed // recursively when parsing subexpressions), and each invocation needs to // know where to stop. // // - nparens is the number of left parens without matches. // - nrelops is the number of relational operators that appear in the expr. // - nexprs is the number of unused expressions. // - rprn is a right paren encountered last. // - done means the expression has been fully parsed. // - get_token is true when a token is needed at the end of an iteration. // - assign is true when an assignment statement was parsed last. // - incdec is true when the previous operator was an inc or dec operator. // - can_assign is true when an assignemnt is valid. // - bin_last is true when the previous instruction was a binary operator. t = p->l.t; pfirst = (p->l.t == BC_LEX_LPAREN); nparens = nrelops = 0; nexprs = 0; ops_bgn = p->ops.len; rprn = done = get_token = assign = incdec = can_assign = false; bin_last = true; // We want to eat newlines if newlines are not a valid ending token. // This is for spacing in things like for loop headers. if (!(flags & BC_PARSE_NOREAD)) { while ((t = p->l.t) == BC_LEX_NLINE) bc_lex_next(&p->l); } // This is the Shunting-Yard algorithm loop. for (; !done && BC_PARSE_EXPR(t); t = p->l.t) { switch (t) { case BC_LEX_OP_INC: case BC_LEX_OP_DEC: { // These operators can only be used with items that can be // assigned to. if (BC_ERR(incdec)) bc_parse_err(p, BC_ERR_PARSE_ASSIGN); bc_parse_incdec(p, &prev, &can_assign, &nexprs, flags); rprn = get_token = bin_last = false; incdec = true; flags &= ~(BC_PARSE_ARRAY); break; } #if BC_ENABLE_EXTRA_MATH case BC_LEX_OP_TRUNC: { // The previous token must have been a leaf expression, or the // operator is in the wrong place. if (BC_ERR(!BC_PARSE_LEAF(prev, bin_last, rprn))) bc_parse_err(p, BC_ERR_PARSE_TOKEN); // I can just add the instruction because // negative will already be taken care of. bc_parse_push(p, BC_INST_TRUNC); rprn = can_assign = incdec = false; get_token = true; flags &= ~(BC_PARSE_ARRAY); break; } #endif // BC_ENABLE_EXTRA_MATH case BC_LEX_OP_MINUS: { bc_parse_minus(p, &prev, ops_bgn, rprn, bin_last, &nexprs); rprn = get_token = can_assign = false; // This is true if it was a binary operator last. bin_last = (prev == BC_INST_MINUS); if (bin_last) incdec = false; flags &= ~(BC_PARSE_ARRAY); break; } // All of this group, including the fallthrough, is to parse binary // operators. case BC_LEX_OP_ASSIGN_POWER: case BC_LEX_OP_ASSIGN_MULTIPLY: case BC_LEX_OP_ASSIGN_DIVIDE: case BC_LEX_OP_ASSIGN_MODULUS: case BC_LEX_OP_ASSIGN_PLUS: case BC_LEX_OP_ASSIGN_MINUS: #if BC_ENABLE_EXTRA_MATH case BC_LEX_OP_ASSIGN_PLACES: case BC_LEX_OP_ASSIGN_LSHIFT: case BC_LEX_OP_ASSIGN_RSHIFT: #endif // BC_ENABLE_EXTRA_MATH case BC_LEX_OP_ASSIGN: { // We need to make sure the assignment is valid. if (!BC_PARSE_INST_VAR(prev)) bc_parse_err(p, BC_ERR_PARSE_ASSIGN); } // Fallthrough. BC_FALLTHROUGH case BC_LEX_OP_POWER: case BC_LEX_OP_MULTIPLY: case BC_LEX_OP_DIVIDE: case BC_LEX_OP_MODULUS: case BC_LEX_OP_PLUS: #if BC_ENABLE_EXTRA_MATH case BC_LEX_OP_PLACES: case BC_LEX_OP_LSHIFT: case BC_LEX_OP_RSHIFT: #endif // BC_ENABLE_EXTRA_MATH case BC_LEX_OP_REL_EQ: case BC_LEX_OP_REL_LE: case BC_LEX_OP_REL_GE: case BC_LEX_OP_REL_NE: case BC_LEX_OP_REL_LT: case BC_LEX_OP_REL_GT: case BC_LEX_OP_BOOL_NOT: case BC_LEX_OP_BOOL_OR: case BC_LEX_OP_BOOL_AND: { // This is true if the operator if the token is a prefix // operator. This is only for boolean not. if (BC_PARSE_OP_PREFIX(t)) { // Prefix operators are only allowed after binary operators // or prefix operators. if (BC_ERR(!bin_last && !BC_PARSE_OP_PREFIX(p->l.last))) bc_parse_err(p, BC_ERR_PARSE_EXPR); } // If we execute the else, that means we have a binary operator. // If the previous operator was a prefix or a binary operator, // then a binary operator is not allowed. else if (BC_ERR(BC_PARSE_PREV_PREFIX(prev) || bin_last)) bc_parse_err(p, BC_ERR_PARSE_EXPR); nrelops += (t >= BC_LEX_OP_REL_EQ && t <= BC_LEX_OP_REL_GT); prev = BC_PARSE_TOKEN_INST(t); bc_parse_operator(p, t, ops_bgn, &nexprs); rprn = incdec = can_assign = false; get_token = true; bin_last = !BC_PARSE_OP_PREFIX(t); flags &= ~(BC_PARSE_ARRAY); break; } case BC_LEX_LPAREN: { // A left paren is *not* allowed right after a leaf expr. if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn))) bc_parse_err(p, BC_ERR_PARSE_EXPR); nparens += 1; rprn = incdec = can_assign = false; get_token = true; // Push the paren onto the operator stack. bc_vec_push(&p->ops, &t); break; } case BC_LEX_RPAREN: { // This needs to be a status. The error is handled in // bc_parse_expr_status(). if (BC_ERR(p->l.last == BC_LEX_LPAREN)) return BC_PARSE_STATUS_EMPTY_EXPR; // The right paren must not come after a prefix or binary // operator. if (BC_ERR(bin_last || BC_PARSE_PREV_PREFIX(prev))) bc_parse_err(p, BC_ERR_PARSE_EXPR); // If there are no parens left, we are done, but we need another // token. if (!nparens) { done = true; get_token = false; break; } nparens -= 1; rprn = true; get_token = bin_last = incdec = false; bc_parse_rightParen(p, &nexprs); break; } case BC_LEX_STR: { // POSIX only allows strings alone. if (BC_IS_POSIX) bc_parse_err(p, BC_ERR_POSIX_EXPR_STRING); // A string is a leaf and cannot come right after a leaf. if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn))) bc_parse_err(p, BC_ERR_PARSE_EXPR); bc_parse_addString(p); get_token = true; bin_last = rprn = false; nexprs += 1; break; } case BC_LEX_NAME: { // A name is a leaf and cannot come right after a leaf. if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn))) bc_parse_err(p, BC_ERR_PARSE_EXPR); get_token = bin_last = false; bc_parse_name(p, &prev, &can_assign, flags & ~BC_PARSE_NOCALL); rprn = (prev == BC_INST_CALL); nexprs += 1; flags &= ~(BC_PARSE_ARRAY); break; } case BC_LEX_NUMBER: { // A number is a leaf and cannot come right after a leaf. if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn))) bc_parse_err(p, BC_ERR_PARSE_EXPR); // The number instruction is pushed in here. bc_parse_number(p); nexprs += 1; prev = BC_INST_NUM; get_token = true; rprn = bin_last = can_assign = false; flags &= ~(BC_PARSE_ARRAY); break; } case BC_LEX_KW_IBASE: case BC_LEX_KW_LAST: case BC_LEX_KW_OBASE: #if BC_ENABLE_EXTRA_MATH case BC_LEX_KW_SEED: #endif // BC_ENABLE_EXTRA_MATH { // All of these are leaves and cannot come right after a leaf. if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn))) bc_parse_err(p, BC_ERR_PARSE_EXPR); prev = t - BC_LEX_KW_LAST + BC_INST_LAST; bc_parse_push(p, prev); get_token = can_assign = true; rprn = bin_last = false; nexprs += 1; flags &= ~(BC_PARSE_ARRAY); break; } case BC_LEX_KW_LENGTH: case BC_LEX_KW_SQRT: case BC_LEX_KW_ABS: #if BC_ENABLE_EXTRA_MATH case BC_LEX_KW_IRAND: #endif // BC_ENABLE_EXTRA_MATH case BC_LEX_KW_ASCIIFY: { // All of these are leaves and cannot come right after a leaf. if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn))) bc_parse_err(p, BC_ERR_PARSE_EXPR); bc_parse_builtin(p, t, flags, &prev); rprn = get_token = bin_last = incdec = can_assign = false; nexprs += 1; flags &= ~(BC_PARSE_ARRAY); break; } case BC_LEX_KW_READ: #if BC_ENABLE_EXTRA_MATH case BC_LEX_KW_RAND: #endif // BC_ENABLE_EXTRA_MATH case BC_LEX_KW_MAXIBASE: case BC_LEX_KW_MAXOBASE: case BC_LEX_KW_MAXSCALE: #if BC_ENABLE_EXTRA_MATH case BC_LEX_KW_MAXRAND: #endif // BC_ENABLE_EXTRA_MATH case BC_LEX_KW_LINE_LENGTH: case BC_LEX_KW_GLOBAL_STACKS: case BC_LEX_KW_LEADING_ZERO: { // All of these are leaves and cannot come right after a leaf. if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn))) bc_parse_err(p, BC_ERR_PARSE_EXPR); // Error if we have read and it's not allowed. else if (t == BC_LEX_KW_READ && BC_ERR(flags & BC_PARSE_NOREAD)) bc_parse_err(p, BC_ERR_EXEC_REC_READ); prev = t - BC_LEX_KW_READ + BC_INST_READ; bc_parse_noArgBuiltin(p, prev); rprn = get_token = bin_last = incdec = can_assign = false; nexprs += 1; flags &= ~(BC_PARSE_ARRAY); break; } case BC_LEX_KW_SCALE: { // This is a leaf and cannot come right after a leaf. if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn))) bc_parse_err(p, BC_ERR_PARSE_EXPR); // Scale needs special work because it can be a variable *or* a // function. bc_parse_scale(p, &prev, &can_assign, flags); rprn = get_token = bin_last = false; nexprs += 1; flags &= ~(BC_PARSE_ARRAY); break; } case BC_LEX_KW_MODEXP: case BC_LEX_KW_DIVMOD: { // This is a leaf and cannot come right after a leaf. if (BC_ERR(BC_PARSE_LEAF(prev, bin_last, rprn))) bc_parse_err(p, BC_ERR_PARSE_EXPR); bc_parse_builtin3(p, t, flags, &prev); rprn = get_token = bin_last = incdec = can_assign = false; nexprs += 1; flags &= ~(BC_PARSE_ARRAY); break; } default: { #ifndef NDEBUG // We should never get here, even in debug builds. bc_parse_err(p, BC_ERR_PARSE_TOKEN); break; #endif // NDEBUG } } if (get_token) bc_lex_next(&p->l); } // Now that we have parsed the expression, we need to empty the operator // stack. while (p->ops.len > ops_bgn) { top = BC_PARSE_TOP_OP(p); assign = top >= BC_LEX_OP_ASSIGN_POWER && top <= BC_LEX_OP_ASSIGN; // There should not be *any* parens on the stack anymore. if (BC_ERR(top == BC_LEX_LPAREN || top == BC_LEX_RPAREN)) bc_parse_err(p, BC_ERR_PARSE_EXPR); bc_parse_push(p, BC_PARSE_TOKEN_INST(top)); // Adjust the number of unused expressions. nexprs -= !BC_PARSE_OP_PREFIX(top); bc_vec_pop(&p->ops); incdec = false; } // There must be only one expression at the top. if (BC_ERR(nexprs != 1)) bc_parse_err(p, BC_ERR_PARSE_EXPR); // Check that the next token is correct. for (i = 0; i < next.len && t != next.tokens[i]; ++i); if (BC_ERR(i == next.len && !bc_parse_isDelimiter(p))) bc_parse_err(p, BC_ERR_PARSE_EXPR); // Check that POSIX would be happy with the number of relational operators. if (!(flags & BC_PARSE_REL) && nrelops) bc_parse_err(p, BC_ERR_POSIX_REL_POS); else if ((flags & BC_PARSE_REL) && nrelops > 1) bc_parse_err(p, BC_ERR_POSIX_MULTIREL); // If this is true, then we might be in a situation where we don't print. // We would want to have the increment/decrement operator not make an extra // copy if it's not necessary. if (!(flags & BC_PARSE_NEEDVAL) && !pfirst) { // We have the easy case if the last operator was an assignment // operator. if (assign) { inst = *((uchar*) bc_vec_top(&p->func->code)); inst += (BC_INST_ASSIGN_POWER_NO_VAL - BC_INST_ASSIGN_POWER); incdec = false; } // If we have an inc/dec operator and we are *not* printing, implement // the optimization to get rid of the extra copy. else if (incdec && !(flags & BC_PARSE_PRINT)) { inst = *((uchar*) bc_vec_top(&p->func->code)); incdec = (inst <= BC_INST_DEC); inst = BC_INST_ASSIGN_PLUS_NO_VAL + (inst != BC_INST_INC && inst != BC_INST_ASSIGN_PLUS); } // This condition allows us to change the previous assignment // instruction (which does a copy) for a NO_VAL version, which does not. // This condition is set if either of the above if statements ends up // being true. if (inst >= BC_INST_ASSIGN_POWER_NO_VAL && inst <= BC_INST_ASSIGN_NO_VAL) { // Pop the previous assignment instruction and push a new one. // Inc/dec needs the extra instruction because it is now a binary // operator and needs a second operand. bc_vec_pop(&p->func->code); if (incdec) bc_parse_push(p, BC_INST_ONE); bc_parse_push(p, inst); } } // If we might have to print... if ((flags & BC_PARSE_PRINT)) { // With a paren first or the last operator not being an assignment, we // *do* want to print. if (pfirst || !assign) bc_parse_push(p, BC_INST_PRINT); } // We need to make sure to push a pop instruction for assignment statements // that will not print. The print will pop, but without it, we need to pop. else if (!(flags & BC_PARSE_NEEDVAL) && (inst < BC_INST_ASSIGN_POWER_NO_VAL || inst > BC_INST_ASSIGN_NO_VAL)) { bc_parse_push(p, BC_INST_POP); } // We want to eat newlines if newlines are not a valid ending token. // This is for spacing in things like for loop headers. // // Yes, this is one case where I reuse a variable for a different purpose; // in this case, incdec being true now means that newlines are not valid. for (incdec = true, i = 0; i < next.len && incdec; ++i) incdec = (next.tokens[i] != BC_LEX_NLINE); if (incdec) { while (p->l.t == BC_LEX_NLINE) bc_lex_next(&p->l); } return BC_PARSE_STATUS_SUCCESS; } /** * Parses an expression with bc_parse_expr_err(), but throws an error if it gets * an empty expression. * @param p The parser. * @param flags The flags for what is valid in the expression. * @param next A set of tokens for what is valid *after* the expression. */ static void bc_parse_expr_status(BcParse *p, uint8_t flags, BcParseNext next) { BcParseStatus s = bc_parse_expr_err(p, flags, next); if (BC_ERR(s == BC_PARSE_STATUS_EMPTY_EXPR)) bc_parse_err(p, BC_ERR_PARSE_EMPTY_EXPR); } void bc_parse_expr(BcParse *p, uint8_t flags) { assert(p); bc_parse_expr_status(p, flags, bc_parse_next_read); } #endif // BC_ENABLED
the_stack_data/36559.c
int primo(unsigned int val) { if (val < 2) { return 0; } for (unsigned int i = 2; i < val; ++i) { if (val % i == 0) { return 0; } } return 1; } unsigned int prossimo_primo(unsigned int x) { if (x < 2) { return 0; } unsigned int y = x + 1; while (primo(y) == 0) { y++; } return y; } int main(void) { unsigned int x; x = prossimo_primo(7); return 0; }
the_stack_data/922041.c
// RUN: %sea abc -O0 --abc-encoding=%abc_encoding %dsa "%s" %abc3_definitions 2>&1 | OutputCheck %s // CHECK: ^unsat$ // Used to avoid llvm to optimize away extern void read(int); int *foo(int *c, int n, int x) { int i; for (i = 0; i < n; i++) c[i] = x; return c; } int main() { int a[10]; /*int *b =*/foo(a, 10, 5); int b[10]; int *c = foo(b, 10, 7); read(c[7]); return 0; }
the_stack_data/97013614.c
#include <stdio.h> #include <string.h> int main() { int n,i,f=0,cnt[10];char s[100]; for (i=0;i<10;i++) cnt[i]=0; puts("Enter a number:"); scanf("%s",s);n=strlen(s); for (i=0;i<n;i++) ++cnt[s[i]-'0']; puts("Repeated digits:"); for (i=0;i<=9;i++) if (cnt[i]>=2) { f=1; printf("%d %d\n",i,cnt[i]); } if (!f) puts("No Repeated Digits"); return 0; }
the_stack_data/242331178.c
#include <stdio.h> #include <complex.h> #include <stdint.h> #include <stdlib.h> #include <math.h> #define TILE_SIZE 512 static void panic(const char* msg) { fprintf(stderr, "panic: %s\n", msg); exit(1); } static inline uint8_t bship(const double complex c) { double complex z = 0; uint8_t retval = 0; while (retval < 255 && cabs(z) < 2) { retval++; z = fabs(creal(z)) + fabs(cimag(z))*I; z *= z; z += c; } return retval; } int main(int argc, char *argv[]) { if (argc != 4){ panic("bad number of arguments"); } const double complex location = atof(argv[1]) + atof(argv[2])*I; const double width = atof(argv[3]); const double step_size = width / TILE_SIZE; uint32_t y; for (y=0; y<TILE_SIZE; y++) { uint8_t row[TILE_SIZE]; uint32_t x; for (x=0; x<TILE_SIZE; x++) { double complex c = location + x*step_size + y*step_size*I; row[x] = bship(c); } (void)fwrite(&row, sizeof(row), 1, stdout); } return 0; }
the_stack_data/157922.c
#include <string.h> #include <assert.h> /** * substring * @param str the origin string. * @param sub the char array to store substring. * @param startIndex the start index. * @param len the count of characters of substring * @return the address of substring. */ char *substring(char str[], char sub[], int startIndex, int len) { if (startIndex < 0 || startIndex > strlen(str) - len) { return NULL; } int j = 0; for (int i = startIndex; i < startIndex + len; i++) { sub[j++] = str[i]; } sub[j] = '\0'; return sub; } void test() { char str[100] = "abc123456"; char sub[100]; substring(str, sub, 3, 6); assert(strcmp(sub, "123456") == 0); } int main() { test(); return 0; }
the_stack_data/154828889.c
// PARAM: --disable exp.unsoundbasic --set ana.activated[+] "'var_eq'" --set ana.activated[+] "'symb_locks'" #include<pthread.h> #include<stdlib.h> struct q { int x; int y; }; struct s { int datum; struct q inside; pthread_mutex_t mutex; } A, B; void *t_fun(void *arg) { pthread_mutex_lock(&A.mutex); B.datum = 5; //RACE pthread_mutex_lock(&A.mutex); return NULL; } int main () { int x; pthread_t id; // struct s *s = malloc(sizeof(struct s)); struct s *s; //struct q *q; int *d; pthread_mutex_t *m; if (x) { s = &A; x++; } else { s = &B; x++; } //q = &s->inside; m = &s->mutex; d = &s->datum; pthread_create(&id,NULL,t_fun,NULL); pthread_mutex_lock(m); *d = 8; //RACE pthread_mutex_unlock(m); return 0; }
the_stack_data/10197.c
/* Set IPv4 source filter. Linux version. Copyright (C) 2004-2016 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Ulrich Drepper <[email protected]>, 2004. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ #include <alloca.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <netinet/in.h> #include <sys/socket.h> int setipv4sourcefilter (int s, struct in_addr interface, struct in_addr group, uint32_t fmode, uint32_t numsrc, const struct in_addr *slist) { /* We have to create an struct ip_msfilter object which we can pass to the kernel. */ size_t needed = IP_MSFILTER_SIZE (numsrc); int use_alloca = __libc_use_alloca (needed); struct ip_msfilter *imsf; if (use_alloca) imsf = (struct ip_msfilter *) alloca (needed); else { imsf = (struct ip_msfilter *) malloc (needed); if (imsf == NULL) return -1; } imsf->imsf_multiaddr = group; imsf->imsf_interface = interface; imsf->imsf_fmode = fmode; imsf->imsf_numsrc = numsrc; memcpy (imsf->imsf_slist, slist, numsrc * sizeof (struct in_addr)); int result = __setsockopt (s, SOL_IP, IP_MSFILTER, imsf, needed); if (! use_alloca) { int save_errno = errno; free (imsf); __set_errno (save_errno); } return result; }
the_stack_data/118426.c
int exported_variable;
the_stack_data/297789.c
#include <stdio.h> void changenum(int a){ a = 1; return; } int main(){ int a = 0; changenum(a); printf("%d\n",a); return 0; }
the_stack_data/29415.c
#include <stdio.h> int main(){ int sum=0, i=100; while(i<=200){ (i%9==0)?printf("%d\n",i),sum+=i,i++:i++;} printf("Sum=%d", sum); }
the_stack_data/380538.c
/* Copyright (C) 1996-2020 Free Software Foundation, Inc. This file is part of the GNU C Library. Contributed by Ulrich Drepper <[email protected]>, 1996. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <https://www.gnu.org/licenses/>. */ #include <netinet/ether.h> struct ether_addr * ether_aton (const char *asc) { static struct ether_addr result; return ether_aton_r (asc, &result); }
the_stack_data/184518598.c
#include <stdio.h> #include <stdlib.h> typedef struct { int codigo ; // codigo do funcionario int qtd_dias_trabalhados ; // qtd de dias que o funcionario trabalhou int * horas_trabalhadas ; // horas trabalhadas em cada dia pelo func . int horasTotal; int salario; int gastoTotal; } Funcionario ; void ler(Funcionario *ficha) { printf("Codigo: "); scanf("%d", &ficha->codigo); printf("Quantidade de dias trabalhados: "); scanf("%d", &ficha->qtd_dias_trabalhados); printf("Horas trabalhadas por dia: "); ficha->horas_trabalhadas = calloc(ficha->qtd_dias_trabalhados, sizeof(int)); for(int j = 0; j < ficha->qtd_dias_trabalhados; j++){ scanf("%d", &ficha->horas_trabalhadas[j]); ficha->horasTotal += ficha->horas_trabalhadas[j]; ficha->salario = ficha->horasTotal * 25; } } void mostrar(Funcionario *ficha) { printf("%d - ", ficha->codigo); printf("%d - ", ficha->horasTotal); printf("R$%d\n", ficha->salario); } int main() { int qtdFuncionarios = 0, gastoTotal = 0, i = 0; Funcionario *ficha; printf("Quantidade de funcionarios: "); scanf("%d", &qtdFuncionarios); ficha = calloc(qtdFuncionarios, sizeof(Funcionario)); printf("\n"); for(i = 0; i < qtdFuncionarios; i++) { printf("--- Funcionario %d ---\n", (i + 1)); ler(&ficha[i]); gastoTotal += ficha[i].salario; } printf("Funcionario - Horas Trabalhadas - Salario\n"); for(i = 0; i < qtdFuncionarios; i++) { mostrar(&ficha[i]); } printf("Total pago aos funcionarios: R$%d", gastoTotal); for(i = 0; i < qtdFuncionarios; i++) { free(ficha[i].horas_trabalhadas); } free(ficha); }
the_stack_data/14199792.c
#include <stddef.h> size_t my_strlen(const char* s) { const char* start = s; while (*s) s++; return s - start; } int foo() { return 0; } int main() { for (size_t i = 0; i < 1000; i++) foo(); return 0; }
the_stack_data/145454301.c
#include <stdio.h> #include <stdlib.h> int main() { int n, p, c, rc = 1, lc = 1, rmax, lmax; scanf("%d", &n); int *tr = (int *) calloc(n, sizeof(int)); scanf("%d", tr); lmax = tr[0]; for (int i = 1; i < n; i++) { scanf("%d", tr + i); if (tr[i] > lmax) { lmax = tr[i]; lc++; } } rmax = tr[n - 1]; for (int i = n - 2; i >= 0; i--) { if (tr[i] > rmax) { rmax = tr[i]; rc++; } } printf("%d\n%d", lc, rc); }
the_stack_data/448033.c
// REQUIRES: solver // RUN: env SOUPER_NO_EXTERNAL_CACHE=1 SOUPER_DYNAMIC_PROFILE=1 SOUPER_SOLVER=%solver %sclang -O %s -o %t // RUN: env SOUPER_PROFILE_TO_STDOUT=1 %t 0 | FileCheck %s -check-prefix=ARG0 // ARG0: count = 0 // RUN: env SOUPER_PROFILE_TO_STDOUT=1 %t 1 | FileCheck %s -check-prefix=ARG1 // ARG1: count = 1 // RUN: env SOUPER_PROFILE_TO_STDOUT=1 %t 2 | FileCheck %s -check-prefix=ARG2 // ARG2: count = 100 // RUN: env SOUPER_PROFILE_TO_STDOUT=1 %t 3 | FileCheck %s -check-prefix=ARG3 // ARG3: count = 101 // RUN: env SOUPER_PROFILE_TO_STDOUT=1 %t 4 | FileCheck %s -check-prefix=ARG4 // ARG4: count = 10000 // RUN: env SOUPER_PROFILE_TO_STDOUT=1 %t 5 | FileCheck %s -check-prefix=ARG5 // ARG5: count = 10001 // RUN: env SOUPER_PROFILE_TO_STDOUT=1 %t 6 | FileCheck %s -check-prefix=ARG6 // ARG6: count = 10100 // RUN: env SOUPER_PROFILE_TO_STDOUT=1 %t 7 | FileCheck %s -check-prefix=ARG7 // ARG7: count = 10101 #include <stdlib.h> volatile int opaque; // this is fragile: any code where Souper can find an optimization that LLVM // misses void souper_opt (void) { int a = opaque; int b = opaque; if (a==b) { if (a>b) { ++opaque; } } } int main(int argc, char *argv[]) { if (argc != 2) abort(); long arg = strtol(argv[1], 0, 10); if (arg<0 || arg>7) abort(); if (arg&1) souper_opt(); int i; for (i=0; i<100; ++i) { if (arg&2) souper_opt(); int j; for (j=0; j<100; ++j) { if (arg&4) souper_opt(); } } return 0; }
the_stack_data/66911.c
#include <string.h> #include <zlib.h> #include <stdio.h> #include <inttypes.h> #include <stdlib.h> #include <assert.h> #define PACKAGE_VERSION "r439" //#define MAQ_LONGREADS #ifdef MAQ_LONGREADS # define MAX_READLEN 128 #else # define MAX_READLEN 64 #endif #define MAX_NAMELEN 36 #define MAQMAP_FORMAT_OLD 0 #define MAQMAP_FORMAT_NEW -1 #define PAIRFLAG_FF 0x01 #define PAIRFLAG_FR 0x02 #define PAIRFLAG_RF 0x04 #define PAIRFLAG_RR 0x08 #define PAIRFLAG_PAIRED 0x10 #define PAIRFLAG_DIFFCHR 0x20 #define PAIRFLAG_NOMATCH 0x40 #define PAIRFLAG_SW 0x80 typedef struct { uint8_t seq[MAX_READLEN]; /* the last base is the single-end mapping quality. */ uint8_t size, map_qual, info1, info2, c[2], flag, alt_qual; uint32_t seqid, pos; int dist; char name[MAX_NAMELEN]; } maqmap1_t; typedef struct { int format, n_ref; char **ref_name; uint64_t n_mapped_reads; maqmap1_t *mapped_reads; } maqmap_t; maqmap_t *maq_new_maqmap(void) { maqmap_t *mm = (maqmap_t*)calloc(1, sizeof(maqmap_t)); mm->format = MAQMAP_FORMAT_NEW; return mm; } void maq_delete_maqmap(maqmap_t *mm) { int i; if (mm == 0) return; for (i = 0; i < mm->n_ref; ++i) free(mm->ref_name[i]); free(mm->ref_name); free(mm->mapped_reads); free(mm); } maqmap_t *maqmap_read_header(gzFile fp) { maqmap_t *mm; int k, len; mm = maq_new_maqmap(); gzread(fp, &mm->format, sizeof(int)); if (mm->format != MAQMAP_FORMAT_NEW) { if (mm->format > 0) { fprintf(stderr, "** Obsolete map format is detected. Please use 'mapass2maq' command to convert the format.\n"); exit(3); } assert(mm->format == MAQMAP_FORMAT_NEW); } gzread(fp, &mm->n_ref, sizeof(int)); mm->ref_name = (char**)calloc(mm->n_ref, sizeof(char*)); for (k = 0; k != mm->n_ref; ++k) { gzread(fp, &len, sizeof(int)); mm->ref_name[k] = (char*)malloc(len * sizeof(char)); gzread(fp, mm->ref_name[k], len); } /* read number of mapped reads */ gzread(fp, &mm->n_mapped_reads, sizeof(uint64_t)); return mm; } void maq2tam_core(gzFile fp, const char *rg) { maqmap_t *mm; maqmap1_t mm1, *m1; int ret; m1 = &mm1; mm = maqmap_read_header(fp); while ((ret = gzread(fp, m1, sizeof(maqmap1_t))) == sizeof(maqmap1_t)) { int j, flag = 0, se_mapq = m1->seq[MAX_READLEN-1]; if (m1->flag) flag |= 1; if ((m1->flag&PAIRFLAG_PAIRED) || ((m1->flag&PAIRFLAG_SW) && m1->flag != 192)) flag |= 2; if (m1->flag == 192) flag |= 4; if (m1->flag == 64) flag |= 8; if (m1->pos&1) flag |= 0x10; if ((flag&1) && m1->dist != 0) { int c; if (m1->dist > 0) { if (m1->flag&(PAIRFLAG_FF|PAIRFLAG_RF)) c = 0; else if (m1->flag&(PAIRFLAG_FR|PAIRFLAG_RR)) c = 1; else c = m1->pos&1; } else { if (m1->flag&(PAIRFLAG_FF|PAIRFLAG_FR)) c = 0; else if (m1->flag&(PAIRFLAG_RF|PAIRFLAG_RR)) c = 1; else c = m1->pos&1; } if (c) flag |= 0x20; } if (m1->flag) { int l = strlen(m1->name); if (m1->name[l-2] == '/') { flag |= (m1->name[l-1] == '1')? 0x40 : 0x80; m1->name[l-2] = '\0'; } } printf("%s\t%d\t", m1->name, flag); printf("%s\t%d\t", mm->ref_name[m1->seqid], (m1->pos>>1)+1); if (m1->flag == 130) { int c = (int8_t)m1->seq[MAX_READLEN-1]; printf("%d\t", m1->alt_qual); if (c == 0) printf("%dM\t", m1->size); else { if (c > 0) printf("%dM%dI%dM\t", m1->map_qual, c, m1->size - m1->map_qual - c); else printf("%dM%dD%dM\t", m1->map_qual, -c, m1->size - m1->map_qual); } se_mapq = 0; // zero SE mapQ for reads aligned by SW } else { if (flag&4) printf("0\t*\t"); else printf("%d\t%dM\t", m1->map_qual, m1->size); } printf("*\t0\t%d\t", m1->dist); for (j = 0; j != m1->size; ++j) { if (m1->seq[j] == 0) putchar('N'); else putchar("ACGT"[m1->seq[j]>>6&3]); } putchar('\t'); for (j = 0; j != m1->size; ++j) putchar((m1->seq[j]&0x3f) + 33); putchar('\t'); if (rg) printf("RG:Z:%s\t", rg); if (flag&4) { // unmapped printf("MF:i:%d\n", m1->flag); } else { printf("MF:i:%d\t", m1->flag); if (m1->flag) printf("AM:i:%d\tSM:i:%d\t", m1->alt_qual, se_mapq); printf("NM:i:%d\tUQ:i:%d\tH0:i:%d\tH1:i:%d\n", m1->info1&0xf, m1->info2, m1->c[0], m1->c[1]); } } if (ret > 0) fprintf(stderr, "Truncated! Continue anyway.\n"); maq_delete_maqmap(mm); } int main(int argc, char *argv[]) { gzFile fp; if (argc == 1) { fprintf(stderr, "Version: %s\n", PACKAGE_VERSION); fprintf(stderr, "Usage: maq2sam <in.map> [<readGroup>]\n"); return 1; } fp = strcmp(argv[1], "-")? gzopen(argv[1], "r") : gzdopen(fileno(stdin), "r"); maq2tam_core(fp, argc > 2? argv[2] : 0); gzclose(fp); return 0; }
the_stack_data/25138707.c
#include <stdio.h> #include <stdlib.h> void vassume(int b){} void vtrace(int a, int b) {} void mainQ(int flag, int u1, int u2) { vassume(u1 > 0 && u2 > 0); int j = 1; int i = 0; if (flag != 0) { i = 0; } else { i = 1; } int i1 = 0; while (i1 < u1) { i1++; i += 2; if (i % 2 == 0) { j += 2; } else j++; } int a = 0; int b = 0; int i2 = 0; while (i2 < u2) { i2++; a++; b += (j - i); } //%%%traces: int a, int b, int i, int j if (flag != 0) { vtrace(a, b); //assert(a ==b); } } void main(int argc, char *argv[]) { mainQ(atoi(argv[1]), atoi(argv[2]), atoi(argv[3])); }
the_stack_data/76699792.c
#include <memory.h> // src: toaruos // todo: all the asm snippets - ?!?!?!?! void* memset(void * dest, int c, size_t n) { asm volatile("rep stosb" : "=c"((int){0}) : "D"(dest), "a"(c), "c"(n) : "flags", "memory"); return dest; }
the_stack_data/95449224.c
#include <stdint.h> // LD1 --> PA5 -- Homework // LD2 --> PB14 -- In Class #define RCC_BASE 0x40021000 #define RCC_AHB2ENR (*((unsigned int *)(RCC_BASE + 0x4C))) #define GPIOB_BASE 0x48000400 #define GPIOB_MODER (*((unsigned int *)(GPIOB_BASE + 0x00))) #define GPIOB_ODR (*((unsigned int *)(GPIOB_BASE + 0x14))) #define GPIOA_BASE 0x48000000 #define GPIOA_MODER (*((unsigned int *)(GPIOA_BASE + 0x00))) #define GPIOA_ODR (*((unsigned int *)(GPIOA_BASE + 0x14))) #define ORD14 (1 << 14) #define ORD5 (1 << 5) #define LED_ON 1 #define LED_OFF 0 #define DELAY_DURATION 100000 void delay(uint32_t iteration); void control_user_led1(uint8_t state, uint32_t duration); void enable_rcc(uint32_t port); void main(void) { // RCC AHB2 peripheral clock enable register (RCC_AHB2ENR) // RCC Base Address: 0x40021000 // Address offset: 0x4C // Set bit[1] to 1 to enable clock to PortB // Set bit[0] to 1 to enable clock to PortA // 1. Enable clock to Peripheral RCC_AHB2ENR |= 0x1; // <TODO> Replace above statement with function call below // enable_rcc(0); // GPIO port mode register (GPIOx_MODER) (x = A..E and H) // GPIOA Base Address: 0x48000000 // Address offset: 0x00 // Set bit[11:10] to 0x01 so --> 0x400 // To enable PA5 as output // Note: GPIOA_MODER reset value = 0xABFFFFFF // So will only need to clear bit 11 GPIOA_MODER &= 0xFFFFF7FF; // GPIO port output data register (GPIOx_ODR) (x = A..E and H) // GPIOA Base Address: 0x48000000 // Address offset: 0x14 // Set bit[5] to 1 --> 0x20; // Turn LED ON // Set bit[5] to 0 --> 0x0; // Turn LED OFF while (1) { control_user_led1(LED_ON, DELAY_DURATION); control_user_led1(LED_OFF, DELAY_DURATION); } }
the_stack_data/1231714.c
#include <time.h> #include <limits.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #define NANO_PER_SEC 1000000000 #define ITERATIONS 1.0e8 long long timediff(struct timespec *start, struct timespec *end) { return (end->tv_sec - start->tv_sec) * NANO_PER_SEC + end->tv_nsec - start->tv_nsec; } uid_t empty_function() { return 0; }; int main(int argc, char **argv) { struct timespec start; struct timespec end; clock_gettime(CLOCK_REALTIME, &start); for (unsigned long i = 0; i < ITERATIONS; i++); clock_gettime(CLOCK_REALTIME, &end); double loop_time = timediff(&start, &end)/(double)ITERATIONS; printf("Loop takes %g nanoseconds\n", loop_time); clock_gettime(CLOCK_REALTIME, &start); for (unsigned long i = 0; i < ITERATIONS; i++) { empty_function(); } clock_gettime(CLOCK_REALTIME, &end); double function_time = timediff(&start, &end)/ITERATIONS - loop_time; printf("Function takes %g nanoseconds\n", function_time); clock_gettime(CLOCK_REALTIME, &start); for (unsigned long i = 0; i < ITERATIONS; i++) { getuid(); } clock_gettime(CLOCK_REALTIME, &end); double syscall_time = timediff(&start, &end)/ITERATIONS - loop_time; printf("getuid() takes %g nanoseconds\n", syscall_time); }
the_stack_data/168893811.c
/* Copyright (C) 1999-2003 Free Software Foundation, Inc. This file is part of the GNU LIBICONV Library. The GNU LIBICONV Library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. The GNU LIBICONV Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with the GNU LIBICONV Library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ /* Creates the aliases2.h table. */ #include <stdio.h> #include <stdlib.h> static void emit_encoding (const char* tag, const char* const* names, size_t n, const char* c_name) { static unsigned int counter = 0; for (; n > 0; names++, n--, counter++) { printf(" S(%s_%u, \"",tag,counter); /* Output *names in upper case. */ { const char* s = *names; for (; *s; s++) { unsigned char c = * (unsigned char *) s; if (c >= 0x80) exit(1); if (c >= 'a' && c <= 'z') c -= 'a'-'A'; putc(c, stdout); } } printf("\", ei_%s )\n", c_name); } } int main (int argc, char* argv[]) { const char * tag = (argc > 1 ? argv[1] : "xxx"); #define DEFENCODING(xxx_names,xxx,xxx_ifuncs1,xxx_ifuncs2,xxx_ofuncs1,xxx_ofuncs2) \ { \ static const char* const names[] = BRACIFY xxx_names; \ emit_encoding(tag,names,sizeof(names)/sizeof(names[0]),#xxx); \ } #define BRACIFY(...) { __VA_ARGS__ } #ifdef USE_AIX #include "encodings_aix.def" #endif #ifdef USE_OSF1 #include "encodings_osf1.def" #endif #ifdef USE_DOS #include "encodings_dos.def" #endif #ifdef USE_EXTRA #include "encodings_extra.def" #endif #undef BRACIFY #undef DEFENCODING fflush(stdout); if (ferror(stdout)) exit(1); exit(0); }
the_stack_data/1056200.c
/* * callofw.c - Open Firmware client interface for 32-bit systems. * This code is intended to be portable to any 32-bit Open Firmware * implementation with a standard client interface that can be * called when Linux is running. */ #include <stdarg.h> typedef unsigned long u32; extern u32 call_firmware(u32 *); #define MAXARGS 20 int callofw(char *name, int numargs, int numres, ...) { va_list ap; u32 argarray[MAXARGS+3]; int argnum = 3; int retval; int *intp; unsigned long flags; argarray[0] = (u32)name; argarray[1] = numargs; argarray[2] = numres; if ((numargs + numres) > MAXARGS) return -1; va_start(ap, numres); while (numargs--) argarray[argnum++] = va_arg(ap, int); retval = call_firmware(argarray); if (retval == 0) { while (numres--) { intp = va_arg(ap, int *); *intp = argarray[argnum++]; } } va_end(ap); return retval; } /* The return value from callofw in all cases is 0 if the attempt to call the function succeeded, nonzero otherwise. That return value is from the gateway function only. Any results from the called function are returned via output argument pointers. Here are call templates for all the standard OFW client services. callofw("test", 1, 1, namestr, &missing); callofw("peer", 1, 1, phandle, &sibling_phandle); callofw("child", 1, 1, phandle, &child_phandle); callofw("parent", 1, 1, phandle, &parent_phandle); callofw("instance-to-package", 1, 1, ihandle, &phandle); callofw("getproplen", 2, 1, phandle, namestr, &proplen); callofw("getprop", 4, 1, phandle, namestr, bufaddr, buflen, &size); callofw("nextprop", 3, 1, phandle, previousstr, bufaddr, &flag); callofw("setprop", 4, 1, phandle, namestr, bufaddr, len, &size); callofw("canon", 3, 1, devspecstr, bufaddr, buflen, &length); callofw("finddevice", 1, 1, devspecstr, &phandle); callofw("instance-to-path", 3, 1, ihandle, bufaddr, buflen, &length); callofw("instance-to-interposed-path", 3, 1, ihandle, bufaddr, buflen, &length); callofw("package-to-path", 3, 1, phandle, bufaddr, buflen, &length); callofw("call-method", numin, numout, in0, in1, ..., &out0, &out1, ...); callofw("open", 1, 1, devspecstr, &ihandle); callofw("close", 1, 0, ihandle); callofw("read", 3, 1, ihandle, addr, len, &actual); callofw("write", 3, 1, ihandle, addr, len, &actual); callofw("seek", 3, 1, ihandle, pos_hi, pos_lo, &status); callofw("claim", 3, 1, virtaddr, size, align, &baseaddr); callofw("release", 2, 0, virtaddr, size); callofw("boot", 1, 0, bootspecstr); callofw("enter", 0, 0); callofw("exit", 0, 0); callofw("chain", 5, 0, virtaddr, size, entryaddr, argsaddr, len); callofw("interpret", numin+1, numout+1, cmdstr, in0, ..., &catchres, &out0, ...); callofw("set-callback", 1, 1, newfuncaddr, &oldfuncaddr); callofw("set-symbol-lookup", 2, 0, symtovaladdr, valtosymaddr); callofw("milliseconds", 0, 1, &ms); */
the_stack_data/31386571.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "generic/VolumetricAdaptiveAveragePooling.c" #else #define START_IND(a,b,c) (int)floor((float)(a * c) / b) #define END_IND(a,b,c) (int)ceil((float)((a + 1) * c) / b) // #define START_IND(a,b,c) a * c / b // #define END_IND(a,b,c) (a + 1) * c / b + ((a + 1) * c % b > 0)?1:0 // 5d tensor B x D x T x H x W static void THNN_(VolumetricAdaptiveAveragePooling_updateOutput_frame)( real *input_p, real *output_p, int64_t sizeD, int64_t isizeT, int64_t isizeH, int64_t isizeW, int64_t osizeT, int64_t osizeH, int64_t osizeW, int64_t istrideD, int64_t istrideT, int64_t istrideH, int64_t istrideW) { int64_t d; #pragma omp parallel for private(d) for (d = 0; d < sizeD; d++) { /* loop over output */ int64_t ot, oh, ow; for(ot = 0; ot < osizeT; ot++) { int istartT = START_IND(ot, osizeT, isizeT); int iendT = END_IND(ot, osizeT, isizeT); int kT = iendT - istartT; for(oh = 0; oh < osizeH; oh++) { int istartH = START_IND(oh, osizeH, isizeH); int iendH = END_IND(oh, osizeH, isizeH); int kH = iendH - istartH; for(ow = 0; ow < osizeW; ow++) { int istartW = START_IND(ow, osizeW, isizeW); int iendW = END_IND(ow, osizeW, isizeW); int kW = iendW - istartW; /* local pointers */ real *ip = input_p + d*istrideD + istartT*istrideT + istartH*istrideH + istartW*istrideW; real *op = output_p + d*osizeT*osizeH*osizeW + ot*osizeH*osizeW + oh*osizeW + ow; /* compute local average: */ real sum = 0; int it, ih, iw; for(it = 0; it < kT; it++) { for(ih = 0; ih < kH; ih++) { for(iw = 0; iw < kW; iw++) { real val = *(ip + it*istrideT + ih*istrideH + iw*istrideW); sum += val; } } } /* set output to local average */ *op = sum / kT / kH / kW; } } } } } void THNN_(VolumetricAdaptiveAveragePooling_updateOutput)( THNNState *state, THTensor *input, THTensor *output, int osizeT, int osizeW, int osizeH) { int dimD = 0; int dimT = 1; int dimH = 2; int dimW = 3; int64_t sizeB = 1; int64_t sizeD = 0; int64_t isizeT = 0; int64_t isizeH = 0; int64_t isizeW = 0; int64_t istrideB = 0; int64_t istrideD = 0; int64_t istrideT = 0; int64_t istrideH = 0; int64_t istrideW = 0; real *input_data = nullptr; real *output_data = nullptr; THNN_ARGCHECK(!input->is_empty() && (input->dim() == 4 || input->dim() == 5), 2, input, "non-empty 4D or 5D (batch mode) tensor expected for input, but got: %s"); if (input->dim() == 5) { istrideB = input->stride(0); sizeB = input->size(0); dimD++; dimT++; dimH++; dimW++; } /* sizes */ sizeD = input->size(dimD); isizeT = input->size(dimT); isizeH = input->size(dimH); isizeW = input->size(dimW); /* strides */ istrideD = input->stride(dimD); istrideT = input->stride(dimT); istrideH = input->stride(dimH); istrideW = input->stride(dimW); /* resize output */ if (input->dim() == 4) { THTensor_(resize4d)(output, sizeD, osizeT, osizeH, osizeW); input_data = THTensor_(data)(input); output_data = THTensor_(data)(output); THNN_(VolumetricAdaptiveAveragePooling_updateOutput_frame)(input_data, output_data, sizeD, isizeT, isizeH, isizeW, osizeT, osizeH, osizeW, istrideD, istrideT, istrideH, istrideW); } else { int64_t b; THTensor_(resize5d)(output, sizeB, sizeD, osizeT, osizeH, osizeW); input_data = THTensor_(data)(input); output_data = THTensor_(data)(output); #pragma omp parallel for private(b) for (b = 0; b < sizeB; b++) { THNN_(VolumetricAdaptiveAveragePooling_updateOutput_frame)(input_data+b*istrideB, output_data+b*sizeD*osizeT*osizeH*osizeW, sizeD, isizeT, isizeH, isizeW, osizeT, osizeH, osizeW, istrideD, istrideT, istrideH, istrideW); } } } static void THNN_(VolumetricAdaptiveAveragePooling_updateGradInput_frame)( real *gradInput_p, real *gradOutput_p, int64_t sizeD, int64_t isizeT, int64_t isizeH, int64_t isizeW, int64_t osizeT, int64_t osizeH, int64_t osizeW) { int64_t d; #pragma omp parallel for private(d) for (d = 0; d < sizeD; d++) { real *gradInput_p_d = gradInput_p + d*isizeT*isizeW*isizeH; real *gradOutput_p_d = gradOutput_p + d*osizeT*osizeW*osizeH; /* calculate average */ int64_t ot, oh, ow; for(ot = 0; ot < osizeT; ot++) { int istartT = START_IND(ot, osizeT, isizeT); int iendT = END_IND(ot, osizeT, isizeT); int kT = iendT - istartT; for(oh = 0; oh < osizeH; oh++) { int istartH = START_IND(oh, osizeH, isizeH); int iendH = END_IND(oh, osizeH, isizeH); int kH = iendH - istartH; for(ow = 0; ow < osizeW; ow++) { int istartW = START_IND(ow, osizeW, isizeW); int iendW = END_IND(ow, osizeW, isizeW); int kW = iendW - istartW; real grad_delta = gradOutput_p_d[ot*osizeH*osizeW + oh*osizeW + ow] / kT / kH / kW; int it, ih, iw; for(it = istartT; it < iendT; it++) { for(ih = istartH; ih < iendH; ih++) { for(iw = istartW; iw < iendW; iw++) { /* update gradient */ gradInput_p_d[it*isizeH*isizeW + ih*isizeW + iw] += grad_delta; } } } } } } } } void THNN_(VolumetricAdaptiveAveragePooling_updateGradInput)( THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput) { int dimD = 0; int dimT = 1; int dimH = 2; int dimW = 3; int64_t sizeB = 1; int64_t sizeD; int64_t isizeT; int64_t isizeH; int64_t isizeW; int64_t osizeT; int64_t osizeH; int64_t osizeW; real *gradInput_data; real *gradOutput_data; /* get contiguous gradOutput */ gradOutput = THTensor_(newContiguous)(gradOutput); /* resize */ THTensor_(resizeAs)(gradInput, input); THTensor_(zero)(gradInput); if (input->dim() == 5) { sizeB = input->size(0); dimD++; dimT++; dimH++; dimW++; } /* sizes */ sizeD = input->size(dimD); isizeT = input->size(dimT); isizeH = input->size(dimH); isizeW = input->size(dimW); osizeT = gradOutput->size(dimT); osizeH = gradOutput->size(dimH); osizeW = gradOutput->size(dimW); /* get raw pointers */ gradInput_data = THTensor_(data)(gradInput); gradOutput_data = THTensor_(data)(gradOutput); /* backprop */ if (input->dim() == 4) { THNN_(VolumetricAdaptiveAveragePooling_updateGradInput_frame)(gradInput_data, gradOutput_data, sizeD, isizeT, isizeH, isizeW, osizeT, osizeH, osizeW); } else { int64_t b; #pragma omp parallel for private(b) for (b = 0; b < sizeB; b++) { THNN_(VolumetricAdaptiveAveragePooling_updateGradInput_frame)(gradInput_data+b*sizeD*isizeT*isizeH*isizeW, gradOutput_data+b*sizeD*osizeT*osizeH*osizeW, sizeD, isizeT, isizeH, isizeW, osizeT, osizeH, osizeW); } } /* cleanup */ THTensor_(free)(gradOutput); } #endif #undef START_IND #undef END_IND
the_stack_data/933293.c
#include <stdio.h> #include <string.h> int y=2, x=1; int main() { int *p = &x + 1; int *q = &y; printf("Addresses: p=%p q=%p\n",(void*)p,(void*)q); // if (p==q) { *p = 11; // does this have undefined behaviour? printf("x=%d y=%d *p=%d *q=%d\n",x,y,*p,*q); // } }
the_stack_data/25137711.c
/* * Copyright 1998-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <stdio.h> unsigned char ebits_to_num[256] = { 0xbd, 0x56, 0xea, 0xf2, 0xa2, 0xf1, 0xac, 0x2a, 0xb0, 0x93, 0xd1, 0x9c, 0x1b, 0x33, 0xfd, 0xd0, 0x30, 0x04, 0xb6, 0xdc, 0x7d, 0xdf, 0x32, 0x4b, 0xf7, 0xcb, 0x45, 0x9b, 0x31, 0xbb, 0x21, 0x5a, 0x41, 0x9f, 0xe1, 0xd9, 0x4a, 0x4d, 0x9e, 0xda, 0xa0, 0x68, 0x2c, 0xc3, 0x27, 0x5f, 0x80, 0x36, 0x3e, 0xee, 0xfb, 0x95, 0x1a, 0xfe, 0xce, 0xa8, 0x34, 0xa9, 0x13, 0xf0, 0xa6, 0x3f, 0xd8, 0x0c, 0x78, 0x24, 0xaf, 0x23, 0x52, 0xc1, 0x67, 0x17, 0xf5, 0x66, 0x90, 0xe7, 0xe8, 0x07, 0xb8, 0x60, 0x48, 0xe6, 0x1e, 0x53, 0xf3, 0x92, 0xa4, 0x72, 0x8c, 0x08, 0x15, 0x6e, 0x86, 0x00, 0x84, 0xfa, 0xf4, 0x7f, 0x8a, 0x42, 0x19, 0xf6, 0xdb, 0xcd, 0x14, 0x8d, 0x50, 0x12, 0xba, 0x3c, 0x06, 0x4e, 0xec, 0xb3, 0x35, 0x11, 0xa1, 0x88, 0x8e, 0x2b, 0x94, 0x99, 0xb7, 0x71, 0x74, 0xd3, 0xe4, 0xbf, 0x3a, 0xde, 0x96, 0x0e, 0xbc, 0x0a, 0xed, 0x77, 0xfc, 0x37, 0x6b, 0x03, 0x79, 0x89, 0x62, 0xc6, 0xd7, 0xc0, 0xd2, 0x7c, 0x6a, 0x8b, 0x22, 0xa3, 0x5b, 0x05, 0x5d, 0x02, 0x75, 0xd5, 0x61, 0xe3, 0x18, 0x8f, 0x55, 0x51, 0xad, 0x1f, 0x0b, 0x5e, 0x85, 0xe5, 0xc2, 0x57, 0x63, 0xca, 0x3d, 0x6c, 0xb4, 0xc5, 0xcc, 0x70, 0xb2, 0x91, 0x59, 0x0d, 0x47, 0x20, 0xc8, 0x4f, 0x58, 0xe0, 0x01, 0xe2, 0x16, 0x38, 0xc4, 0x6f, 0x3b, 0x0f, 0x65, 0x46, 0xbe, 0x7e, 0x2d, 0x7b, 0x82, 0xf9, 0x40, 0xb5, 0x1d, 0x73, 0xf8, 0xeb, 0x26, 0xc7, 0x87, 0x97, 0x25, 0x54, 0xb1, 0x28, 0xaa, 0x98, 0x9d, 0xa5, 0x64, 0x6d, 0x7a, 0xd4, 0x10, 0x81, 0x44, 0xef, 0x49, 0xd6, 0xae, 0x2e, 0xdd, 0x76, 0x5c, 0x2f, 0xa7, 0x1c, 0xc9, 0x09, 0x69, 0x9a, 0x83, 0xcf, 0x29, 0x39, 0xb9, 0xe9, 0x4c, 0xff, 0x43, 0xab, }; unsigned char num_to_ebits[256] = { 0x5d, 0xbe, 0x9b, 0x8b, 0x11, 0x99, 0x6e, 0x4d, 0x59, 0xf3, 0x85, 0xa6, 0x3f, 0xb7, 0x83, 0xc5, 0xe4, 0x73, 0x6b, 0x3a, 0x68, 0x5a, 0xc0, 0x47, 0xa0, 0x64, 0x34, 0x0c, 0xf1, 0xd0, 0x52, 0xa5, 0xb9, 0x1e, 0x96, 0x43, 0x41, 0xd8, 0xd4, 0x2c, 0xdb, 0xf8, 0x07, 0x77, 0x2a, 0xca, 0xeb, 0xef, 0x10, 0x1c, 0x16, 0x0d, 0x38, 0x72, 0x2f, 0x89, 0xc1, 0xf9, 0x80, 0xc4, 0x6d, 0xae, 0x30, 0x3d, 0xce, 0x20, 0x63, 0xfe, 0xe6, 0x1a, 0xc7, 0xb8, 0x50, 0xe8, 0x24, 0x17, 0xfc, 0x25, 0x6f, 0xbb, 0x6a, 0xa3, 0x44, 0x53, 0xd9, 0xa2, 0x01, 0xab, 0xbc, 0xb6, 0x1f, 0x98, 0xee, 0x9a, 0xa7, 0x2d, 0x4f, 0x9e, 0x8e, 0xac, 0xe0, 0xc6, 0x49, 0x46, 0x29, 0xf4, 0x94, 0x8a, 0xaf, 0xe1, 0x5b, 0xc3, 0xb3, 0x7b, 0x57, 0xd1, 0x7c, 0x9c, 0xed, 0x87, 0x40, 0x8c, 0xe2, 0xcb, 0x93, 0x14, 0xc9, 0x61, 0x2e, 0xe5, 0xcc, 0xf6, 0x5e, 0xa8, 0x5c, 0xd6, 0x75, 0x8d, 0x62, 0x95, 0x58, 0x69, 0x76, 0xa1, 0x4a, 0xb5, 0x55, 0x09, 0x78, 0x33, 0x82, 0xd7, 0xdd, 0x79, 0xf5, 0x1b, 0x0b, 0xde, 0x26, 0x21, 0x28, 0x74, 0x04, 0x97, 0x56, 0xdf, 0x3c, 0xf0, 0x37, 0x39, 0xdc, 0xff, 0x06, 0xa4, 0xea, 0x42, 0x08, 0xda, 0xb4, 0x71, 0xb0, 0xcf, 0x12, 0x7a, 0x4e, 0xfa, 0x6c, 0x1d, 0x84, 0x00, 0xc8, 0x7f, 0x91, 0x45, 0xaa, 0x2b, 0xc2, 0xb1, 0x8f, 0xd5, 0xba, 0xf2, 0xad, 0x19, 0xb2, 0x67, 0x36, 0xf7, 0x0f, 0x0a, 0x92, 0x7d, 0xe3, 0x9d, 0xe9, 0x90, 0x3e, 0x23, 0x27, 0x66, 0x13, 0xec, 0x81, 0x15, 0xbd, 0x22, 0xbf, 0x9f, 0x7e, 0xa9, 0x51, 0x4b, 0x4c, 0xfb, 0x02, 0xd3, 0x70, 0x86, 0x31, 0xe7, 0x3b, 0x05, 0x03, 0x54, 0x60, 0x48, 0x65, 0x18, 0xd2, 0xcd, 0x5f, 0x32, 0x88, 0x0e, 0x35, 0xfd, }; main() { int i, j; for (i = 0; i < 256; i++) { for (j = 0; j < 256; j++) if (ebits_to_num[j] == i) { printf("0x%02x,", j); break; } } }
the_stack_data/69907.c
static const char xnvme_3p_fio[] = "fio;git-describe:fio-3.23";
the_stack_data/153269583.c
#include <string.h> #define min(a, b) (((a) < (b)) ? (a) : (b)) #define trimin(a, b, c) (min(min(a, b), c)) //the minimum of a,b,c int minDistance(char *word1, char *word2) { int N1 = strlen(word1), N2 = strlen(word2); int dp[N1 + 1][N2 + 1]; dp[0][0] = 0; for (int i = 0; i < N1; ++i) dp[i + 1][0] = dp[i][0] + 1; for (int j = 0; j < N2; ++j) dp[0][j + 1] = dp[0][j] + 1; for (int i = 0; i < N1; ++i) { for (int j = 0; j < N2; ++j) { if (word1[i] == word2[j]) dp[i + 1][j + 1] = dp[i][j]; else dp[i + 1][j + 1] = trimin(dp[i][j], dp[i + 1][j], dp[i][j + 1]) + 1; } } return dp[N1][N2]; }
the_stack_data/147878.c
int fact(int n){ if(n <= 1){ return 1; } else{ return n * fact(n - 1); } }
the_stack_data/25136499.c
#include <unistd.h> #include <sys/ipc.h> #include <sys/msg.h> #include <stdio.h> #include <stdlib.h> typedef struct { char name[20]; int age; }Person; typedef struct { long type; Person person; }Msg; int main(int argc, char *argv) { int i, res; int id; Msg msg[10] = { {1, {"Luffy", 17}}, {1, {"Zoro", 19}}, {2, {"Nami", 18}}, {2, {"Usopo", 17}}, {1, {"Sanji", 19}}, {3, {"Chopper", 15}}, {4, {"Robin", 28}}, {4, {"Franky", 34}}, {5, {"Brook", 88}}, {6, {"Sunny", 2}} }; id = msgget(0x8888, IPC_CREAT | 0664); for (i = 0; i < 10; ++i) { res = msgsnd(id, &msg[i], sizeof(Person), 0); } return 0; }
the_stack_data/26403.c
// to see the error, enter a non-integer value to terminate the loop // on the first iteration #include <stdio.h> int main() { int count = 0; int sum = 0; int num; while (scanf("%d", &num) == 1) { count++; sum += num; } printf("Avg: %d\n", sum/count); return 0; }
the_stack_data/589250.c
extern void __VERIFIER_error() __attribute__ ((__noreturn__)); void __VERIFIER_assert(int cond) { if(!(cond)) { ERROR: __VERIFIER_error(); } } #define N 50 int main ( ) { int a[N]; int i = 0; while ( i < N ) { a[i] = 42; i = i + 1; } i = 0; while ( i < N ) { a[i] = 43; i = i + 1; } i = 0; while ( i < N ) { a[i] = 44; i = i + 1; } i = 0; while ( i < N ) { a[i] = 45; i = i + 1; } i = 0; while ( i < N ) { a[i] = 46; i = i + 1; } i = 0; while ( i < N ) { a[i] = 47; i = i + 1; } i = 0; while ( i < N ) { a[i] = 48; i = i + 1; } i = 0; while ( i < N ) { a[i] = 49; i = i + 1; } i = 0; while ( i < N ) { a[i] = 50; i = i + 1; } int x; for ( x = 0 ; x < N ; x++ ) { __VERIFIER_assert( a[x] == 50 ); } return 0; }
the_stack_data/86074683.c
/* Copyright (c) Microsoft Corporation. All rights reserved. */ typedef struct _PA { int i; } PHYSICAL_ADDRESS; typedef struct { struct { PHYSICAL_ADDRESS f; } t; } S, *PS; func(PHYSICAL_ADDRESS p) { p.i = 10; } func2(S s) { s.t.f.i = 10; } main() { PS d; d = (PS)malloc(sizeof(S)); func(d->t.f); func2((S)*d); }
the_stack_data/117430.c
#include <stdio.h> void bubblesort(int *array,int len){ int temp,i,j; for(i = 0;i < len;i++){ int flag = 0; for(j = i;j < len-1;j++){ if(array[j+1] < array[j]){ temp = array[j]; array[j] = array[j+1]; array[j+1] = temp; flag = 1; } } if(flag == 0){break;} } } int main(){ int array[] = {1,2,56,3,4,5,64,67,12,32}; int len = sizeof(array) / sizeof(array[0]); bubblesort(array,len); for(int i = 0;i < len;i++){ printf("%d\n",array[i]); } }
the_stack_data/130376.c
// RUN: %clang_analyze_cc1 -analyzer-store=region -verify %s \ // RUN: -analyzer-checker=core \ // RUN: -analyzer-checker=unix \ // RUN: -analyzer-checker=core.uninitialized \ // RUN: -analyzer-config unix.DynamicMemoryModeling:Optimistic=true typedef __typeof(sizeof(int)) size_t; void *malloc(size_t); void free(void *); char stackBased1 () { char buf[2]; buf[0] = 'a'; return buf[1]; // expected-warning{{Undefined}} } char stackBased2 () { char buf[2]; buf[1] = 'a'; return buf[0]; // expected-warning{{Undefined}} } // Exercise the conditional visitor. Radar://10105448 char stackBased3 (int *x) { char buf[2]; int *y; buf[0] = 'a'; if (!(y = x)) { return buf[1]; // expected-warning{{Undefined}} } return buf[0]; } char heapBased1 () { char *buf = malloc(2); buf[0] = 'a'; char result = buf[1]; // expected-warning{{undefined}} free(buf); return result; } char heapBased2 () { char *buf = malloc(2); buf[1] = 'a'; char result = buf[0]; // expected-warning{{undefined}} free(buf); return result; }
the_stack_data/62636876.c
#include <stdio.h> #include <string.h> int x=1; void user_memcpy2(unsigned char* dest, unsigned char *src, size_t n) { while (n > 0) { *dest = ((*src) ^ 1) ^ 1; src += 1; dest += 1; n -= 1; } } int main() { int *p = &x; int *q; user_memcpy2((unsigned char*)&q, (unsigned char*)&p, sizeof(p)); *q = 11; // is this free of undefined behaviour? printf("*p=%d *q=%d\n",*p,*q); }
the_stack_data/212642062.c
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> /* The function gets a digit and a number, and checks several digits in a large mixer from the received number */ unsigned count_larger(unsigned n, unsigned x); // check functions void main() { unsigned int num, digit; printf("Enter an integer number\n"); scanf("%u", &num); printf("Enter digit "); scanf("%u", &digit); printf("There are %u digits in the number bigger than %u\n", count_larger(num, digit), digit); system("pause"); } unsigned count_larger(unsigned n, unsigned x) { if (n > 0) { if (n % 10 > x) return 1 + count_larger(n / 10, x); return count_larger(n / 10, x); } return 0; }
the_stack_data/150142065.c
#include <stdio.h> int main() { double nc; for (nc = 0; getchar() != EOF; ++nc); printf("%1f\n", nc); }
the_stack_data/390462.c
/*Almost every C program has the below line, the #include preprocessor directive is used to instruct the compiler which files to load before compiling the program. All preprocessor commands begin with # */ #include<stdio.h> /*The #define preprocessor directive is often used to create abbreviations for code segments*/ #define Hi printf("Hi There."); /*It can be used, or misused, for rather innovative uses*/ #define start int main(){ #define end return 0;} start Hi /*And here's the nice part, want your compiler to talk to you ? Just use the #warning pragma if you are using a C99 compliant compiler like GCC*/ #warning "Don't you have anything better to do ?" #ifdef __unix__ #warning "What are you doing still working on Unix ?" printf("\nThis is an Unix system."); #elif _WIN32 #warning "You couldn't afford a 64 bit ?" printf("\nThis is a 32 bit Windows system."); #elif _WIN64 #warning "You couldn't afford an Apple ?" printf("\nThis is a 64 bit Windows system."); #endif end /*Enlightened ?*/
the_stack_data/40763587.c
/* * Copyright (c) 2015 Dmitry V. Levin <[email protected]> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #if defined FSTATAT_NAME && defined HAVE_FSTATAT \ && defined HAVE_FTRUNCATE && defined HAVE_FUTIMENS # include <errno.h> # include <fcntl.h> # include <stdio.h> # include <time.h> # include <unistd.h> # include <sys/stat.h> #if defined MAJOR_IN_SYSMACROS # include <sys/sysmacros.h> #elif defined MAJOR_IN_MKDEV # include <sys/mkdev.h> #else # include <sys/types.h> #endif static void print_ftype(const unsigned int mode) { if (S_ISREG(mode)) printf("S_IFREG"); else if (S_ISDIR(mode)) printf("S_IFDIR"); else if (S_ISCHR(mode)) printf("S_IFCHR"); else if (S_ISBLK(mode)) printf("S_IFBLK"); else printf("%#o", mode & S_IFMT); } static void print_perms(const unsigned int mode) { printf("%#o", mode & ~S_IFMT); } static void print_time(const time_t t) { if (!t) { printf("0"); return; } struct tm *p = localtime(&t); if (p) printf("%02d/%02d/%02d-%02d:%02d:%02d", p->tm_year + 1900, p->tm_mon + 1, p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec); else printf("%llu", (unsigned long long) t); } static void print_stat(const struct stat *st) { printf("{st_dev=makedev(%u, %u)", (unsigned int) major(st->st_dev), (unsigned int) minor(st->st_dev)); printf(", st_ino=%Lu", (unsigned long long) st->st_ino); printf(", st_mode="); print_ftype(st->st_mode); printf("|"); print_perms(st->st_mode); printf(", st_nlink=%u", (unsigned int) st->st_nlink); printf(", st_uid=%u", (unsigned int) st->st_uid); printf(", st_gid=%u", (unsigned int) st->st_gid); printf(", st_blksize=%u", (unsigned int) st->st_blksize); printf(", st_blocks=%u", (unsigned int) st->st_blocks); switch (st->st_mode & S_IFMT) { case S_IFCHR: case S_IFBLK: printf(", st_rdev=makedev(%u, %u)", (unsigned int) major(st->st_rdev), (unsigned int) minor(st->st_rdev)); break; default: printf(", st_size=%Lu", (unsigned long long) st->st_size); } printf(", st_atime="); print_time(st->st_atime); if (st->st_atim.tv_nsec) printf(".%09lu", (unsigned long) st->st_atim.tv_nsec); printf(", st_mtime="); print_time(st->st_mtime); if (st->st_mtim.tv_nsec) printf(".%09lu", (unsigned long) st->st_mtim.tv_nsec); printf(", st_ctime="); print_time(st->st_ctime); if (st->st_ctim.tv_nsec) printf(".%09lu", (unsigned long) st->st_ctim.tv_nsec); printf("}"); } int main(void) { static const char sample[] = FSTATAT_NAME ".sample"; static const struct timespec ts[] = { {-10843, 135}, {-10841, 246} }; const off_t size = 46118400291; struct stat st; (void) close(0); if (open(sample, O_RDWR | O_CREAT | O_TRUNC, 0640)) { perror(sample); return 77; } if (ftruncate(0, size)) { perror("ftruncate"); return 77; } if (futimens(0, ts)) { perror("futimens"); return 77; } if (fstatat(AT_FDCWD, sample, &st, AT_SYMLINK_NOFOLLOW)) { perror("fstatat"); return 77; } (void) unlink(sample); printf("%s(AT_FDCWD, \"%s\", ", FSTATAT_NAME, sample); print_stat(&st); puts(", AT_SYMLINK_NOFOLLOW) = 0"); puts("+++ exited with 0 +++"); return 0; } #else int main(void) { return 77; } #endif
the_stack_data/23575145.c
#include <stdio.h> #include <ctype.h> int main(void) { FILE *file = NULL; int symbol = 0, columns = 0, rows = 0; // Attempt to open the file "file.txt" with reading persmissions. file = fopen("file.txt", "r"); // It succeeded! if (file != NULL) { do { // Obtain a single character from the file. symbol = fgetc(file); // Read character by character to determine the amount of columns on the first row. // Because every number is followed by a whitespace this equals the amount of items on a row. if (rows == 0 && (isspace(symbol) || feof(file))) { columns++; } // Every row is followed by a newline. But the last one needn't be. if (symbol == '\n' || feof(file)) { rows++; } } while (symbol != EOF); // Some error occurred during reading. if (ferror(file)) { printf("Error on reading from file.\n"); } // No errors occurred, print the results. else { printf("The file contains %d row(s) and %d column(s).\n", rows, columns); } // Close the file. fclose(file); } // Opening the input file failed. else { perror("Error on opening the input file"); } return 0; }
the_stack_data/43886577.c
/* { dg-do compile { target { ! x32 } } } */ /* { dg-options "-O -fschedule-insns -fcheck-pointer-bounds -mmpx" } */ void bar(int *a, int *b, int *c, int *d, int *e, int *f); int foo (int *a, int *b, int *c, int *d, int *e, int *f) { bar (a, b, c, d, e, f); return *f; }
the_stack_data/161080794.c
/* C Primer Plus - Ch.6 - Problem 3 * @reproduced by yoonBot */ #include <stdio.h> #include <stdlib.h> int main(){ for (char start = 'F'; start >= 'A'; start--){ for (char current = 'F'; current >= start; current--){ printf("%c ", current); } printf("\n"); } return 0; }
the_stack_data/74518.c
foo() { int i; int d; if (d <= -1) { while (i >=0) i = i + d; } } main () { foo (); }
the_stack_data/115963.c
#include <stdio.h> int main() { printf("Hello World\n"); return 0; // 0 when all is right // 1, void or other number is has an error }
the_stack_data/575881.c
// COMP1521 19t2 ... virtual memory simulator #include <assert.h> #include <err.h> #include <stdio.h> #include <stdlib.h> #include <sysexits.h> #define PAGESIZE 4096 #define PAGEBITS 12 #define actionName(A) (((A) == 'R') ? "read from" : "write to") typedef unsigned int uint; // Page Table Entries typedef struct PTE { struct { uint loaded :1; uint modified :1; } status; int frameNo; // -1 if page not loaded int lastAccessed; // -1 if never accessed } PTE; // Global state: static PTE *PageTable; // process page table static int *MemFrames; // memory (each frame holds page #, or -1 if empty) static uint nPages, // how many process pages nFrames, // how many memory frames nLoads = 0, // how many page loads nSaves = 0, // how many page writes (after modification) nReplaces = 0, // how many Page replacements clock = 0; // clock ticks // Functions: int physicalAddress (uint vAddr, char action); void initPageTable (void); void initMemFrames (void); void showState (void); // main: // read memory references // maintain VM data structures // argv[1] = nPages, argv[2] = nFrames // stdin contains lines of form // R Address // W Address // R = read a byte, W = write a byte, Address = byte address // Address is mapped to a page reference as per examples in lectures // Note: pAddr is signed, because -ve used for errors int main (int argc, char *argv[]) { setbuf (stdout, NULL); if (argc < 3) errx (EX_USAGE, "usage: %s <n-pages> <n-frames>", argv[0]); // read command-line arguments if ((nPages = strtol (argv[1], NULL, 10)) < 1) errx (EX_USAGE, "invalid n-pages '%s'", argv[1]); if ((nFrames = strtol (argv[2], NULL, 10)) < 1) errx (EX_USAGE, "invalid n-frames '%s'", argv[2]); initPageTable (); initMemFrames (); char line[BUFSIZ]; // line buffer while (fgets (line, BUFSIZ, stdin) != NULL) { // get next line; check valid (barely) char action; uint vAddr; if (! ((sscanf (line, "%c %d\n", &action, &vAddr) == 2) && (action == 'R' || action == 'W'))) { warnx ("invalid input '%s', ignoring...", line); continue; } // do address mapping int pAddr = physicalAddress (vAddr, action); if (pAddr < 0) errx (EX_SOFTWARE, "invalid address %d", vAddr); // debugging ... printf ( "\n@ t=%d, %s pA=%d (vA=%d)\n", clock, actionName (action), pAddr, vAddr ); // tick clock and show state showState (); clock++; } printf ( "\n#loads = %d, #saves = %d, #replacements = %d\n", nLoads, nSaves, nReplaces ); return EXIT_SUCCESS; } // map virtual address to physical address // handles regular references, page faults and invalid addresses int physicalAddress (uint vAddr, char action) { //physical address int pAddr; uint offset; int frameNum = -2; int replaceFrame; //max = nPages * pageSize if(vAddr < 0 || vAddr >= PAGESIZE * nPages) { return -1; } int pageNum = (int)vAddr / PAGESIZE; PTE *p = &PageTable[pageNum]; //if the page is already loaded if(p->status.loaded == 1) { if(action == 'W') { p->status.modified = 1; } p->lastAccessed = (int)clock; //compute physical address offset = vAddr % PAGESIZE; frameNum = p->frameNo; pAddr = frameNum * PAGESIZE + offset; //the page haven't been loaded } else { for(uint i = 0; i < nFrames ; i++) { //find an unused frame if(MemFrames[i] == -1) { MemFrames[i] = pageNum; p->lastAccessed = (int)clock; p->frameNo = i; frameNum = i; break; } } if(frameNum == -2) { //find the least unsed page PTE *leastUsed; int lastAccessedNum = (int)clock; for(uint i = 0; i < nPages; i++) { if(PageTable[i].lastAccessed < lastAccessedNum && PageTable[i].lastAccessed != -1) { lastAccessedNum = PageTable[i].lastAccessed; leastUsed = &PageTable[i]; replaceFrame = leastUsed->frameNo; } } if(leastUsed->status.modified != 0) { nSaves++; } //set as unloaded leastUsed->status.loaded = 0; leastUsed->status.modified = 0; leastUsed->frameNo = -1; leastUsed->lastAccessed = -1; nReplaces++; //use that frame MemFrames[replaceFrame] = pageNum; p->frameNo = replaceFrame; frameNum = replaceFrame; p->lastAccessed = (int)clock; } //set status p->status.loaded = 1; if(action == 'W') { p->status.modified = 1; } nLoads++; //calculate physical address offset = vAddr % PAGESIZE; pAddr = frameNum * PAGESIZE + offset; } return pAddr; } // allocate and initialise Page Table void initPageTable (void) { if ((PageTable = calloc (nPages, sizeof (PTE))) == NULL) err (EX_OSERR, "couldn't allocate PageTable"); for (uint i = 0; i < nPages; i++) PageTable[i] = (PTE) { .status = { .loaded = 0, .modified = 0 }, .frameNo = -1, .lastAccessed = -1 }; } // allocate and initialise Memory Frames void initMemFrames (void) { if ((MemFrames = calloc (nFrames, sizeof (int))) == NULL) err (EX_OSERR, "couldn't allocate MemFrames"); for (uint i = 0; i < nFrames; i++) MemFrames[i] = -1; } // dump contents of PageTable and MemFrames void showState (void) { printf ("\nPageTable (Stat,Acc,Frame)\n"); for (uint pno = 0; pno < nPages; pno++) { PTE *p = &PageTable[pno]; printf ( "[%2d] %c%c, %2d, %2d", pno, p->status.loaded ? 'L' : '-', p->status.modified ? 'M' : '-', p->lastAccessed, p->frameNo ); int f = p->frameNo; if (f >= 0) printf (" @ %d", f * PAGESIZE); printf ("\n"); } printf ("MemFrames\n"); for (uint fno = 0; fno < nFrames; fno++) printf ( "[%2d] %2d @ %d\n", fno, MemFrames[fno], fno * PAGESIZE ); }
the_stack_data/156393254.c
void abort(); int add(int a, int b) { return a + b; } int sub(int a, int b) { return a - b; } int mul(int a, int b) { return a * b; } int div(int a, int b) { return a / b; } int rem(int a, int b) { return a % b; } long arr[5] = { (long)&add, (long)&sub, (long)&mul, (long)&div, (long)&rem }; int main() { int i; int sum = 0; for (i = 0; i < 10000; i++) { int (*p)(int x, int y) = (int (*)(int x, int y))arr[i % 5]; sum += p(i, 2); } if (sum != 44991000) { abort(); } }
the_stack_data/889533.c
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% This software is copyright (C) by the Lawrence Berkeley Laboratory. Permission is granted to reproduce this software for non-commercial purposes provided that this notice is left intact. It is acknowledged that the U.S. Government has rights to this software under Contract DE-AC03-765F00098 between the U.S. Department of Energy and the University of California. This software is provided as a professional and academic contribution for joint exchange. Thus, it is experimental, and is provided ``as is'', with no warranties of any kind whatsoever, no support, no promise of updates, or printed documentation. By using this software, you acknowledge that the Lawrence Berkeley Laboratory and Regents of the University of California shall have no liability with respect to the infringement of other copyrights by any part of this software. For further information about this notice, contact William Johnston, Bld. 50B, Rm. 2239, Lawrence Berkeley Laboratory, Berkeley, CA, 94720. ([email protected]) For further information about this software, contact: Jin Guojun Bld. 50B, Rm. 2275, Lawrence Berkeley Laboratory, Berkeley, CA, 94720. [email protected] %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% * * c_array.c a collection of routines for handeling * dynamically allocated arrays in C. * * Brian Tierney LBL * * This routines allocate and access array by creating arrays of pointers. * The reason for these routines are speed and code readability. Allocating * arrays in this manner means that elements can be accessed by pointers * instead of by a multiplication and an addition. This method uses more * memory, but on a machine with plenty of memory the increase in speed * is worth it. * * for example, this: * * for (r = 0; r < nrow; r++) * for (c = 0; c < ncol; c++) { * pixel = image[r][c]; * * is faster and more readable (in my opinion), than this: * * for (r = 0; r < nrow; r++) * for (c = 0; c < ncol; c++) { * pixel = image[r * nrow + c]; */ /* routines in this file: alloc_3d_byte_array(nx,ny,nz) alloc_2d_byte_array(nx,ny) read_3d_byte_array(fp,array,nx,ny,nz) read_2d_byte_array(fp,array,nx ,ny) write_3d_byte_array(fp,array,nx,ny,nz) write_2d_byte_array(fp,array,nx,ny) free_3d_byte_array(array) free_2d_byte_array(array) ** and same routines for short, int, and float * * all read/write routines return a 0 if successful and 1 otherwise * * * sample use with hips images: r=rows, c=cols, f = frames * 2D case: * u_char **pic; * pic = alloc_2d_byte_array(r,c); * read_2d_byte_array(stdin, pic1, r,c); * * for (i = 0; i < r; i++) * for (j = 0; j < c; j++) { * want column to vary fastest * * val = pic[i][j]; * } * write_2d_byte_array(stdout, pic2, r,c); * **************************************************** * 3D case: * u_char **pic; * pic = alloc_3d_byte_array(f,r,c); * * read_3d_byte_array(stdin, pic, f,r,c); * * for (i = 0; i < f; i++) * for (j = 0; j < r; j++) * for(k=0; k< c; k++) { * vary col fastest, frame slowest * * val = pic[i][j][k]; */ /***********************************************************************/ /* COPYRIGHT NOTICE *******************************************/ /***********************************************************************/ /* This program is copyright (C) 1990, Regents of the University of California. Anyone may reproduce this software, in whole or in part, provided that: (1) Any copy or redistribution must show the Regents of the University of California, through its Lawrence Berkeley Laboratory, as the source, and must include this notice; (2) Any use of this software must reference this distribu- tion, state that the software copyright is held by the Regents of the University of California, and that the software is used by their permission. It is acknowledged that the U.S. Government has rights to this software under Contract DE-AC03-765F00098 between the U.S. Department of Energy and the University of California. This software is provided as a professional academic contribution for joint exchange. Thus it is experimental, is provided ``as is'', with no warranties of any kind whatsoever, no support, promise of updates, or printed documentation. Bug reports or fixes may be sent to the author, who may or may not act on them as he desires. */ /* Author: Brian L. Tierney * Lawrence Berkeley Laboratory * Imaging and Distributed Computing Group * email: [email protected] */ #include <stdio.h> #include <sys/types.h> #define Calloc(x,y) (y *)calloc((unsigned)(x), sizeof(y)) #define Fread(a,b,c,d) fread((char *)(a), b, (int)(c), d) #define Fwrite(a,b,c,d) fwrite((char *)(a), b, (int)(c), d) void *calloc(),free(); /*********************************/ u_char *** alloc_3d_byte_array(nx,ny,nz) /* in hips terminology: col,row,frame */ int nx,ny,nz; { u_char ***array; register int i, j; /* allocate 3-d array for input image data */ /* allocate 2 arrays of pointers */ if ((array = Calloc(nx, u_char **)) == NULL) perror("calloc error: array "); if ((array[0] = Calloc(nx * ny, u_char *)) == NULL) perror("calloc error: array "); /* allocate array for data */ if ((array[0][0] = Calloc(nx * ny * nz, u_char)) == NULL) perror("calloc error: array "); /* initialize pointer arrays */ for (i = 1; i < ny; i++) array[0][i] = **array + (nz * i); for (i = 1; i < nx; i++) { array[i] = *array + (ny * i); array[i][0] = **array + (nz * ny * i); for (j = 1; j < ny; j++)/* initialize pointer array */ array[i][j] = array[i][0] + (nz * j); } return(array); } /**********************************/ u_char ** alloc_2d_byte_array(nx,ny) int nx,ny; { u_char **array; register int i; /* allocate 2-d array for input image data */ /* allocate array of pointers */ if ((array = Calloc(nx, u_char *)) == NULL) perror("calloc error: array "); /* allocate array for data */ if ((array[0] = Calloc(nx * ny, u_char)) == NULL) perror("calloc error: array "); /* initialize pointer arrays */ for (i = 1; i < nx; i++) array[i] = array[0] + (ny * i); return(array); } /**********************************/ char ** alloc_2d_char_array(nx,ny) int nx,ny; { char **array; register int i; /* allocate 2-d array for input image data */ /* allocate array of pointers */ if ((array = Calloc(nx, char *)) == NULL) perror("calloc error: array "); /* allocate array for data */ if ((array[0] = Calloc(nx * ny, char)) == NULL) perror("calloc error: array "); /* initialize pointer arrays */ for (i = 1; i < nx; i++) array[i] = array[0] + (ny * i); return(array); } /********************************/ int read_3d_byte_array(fp,array,nx,ny,nz) FILE *fp; u_char ***array; int nx,ny,nz; { long rsize; rsize = nx * ny * nz; if (Fread(array[0][0], sizeof(u_char), rsize, fp) != rsize) { perror("\n error reading file\n"); return(-1); } return(0); } /********************************/ int read_2d_byte_array(fp,array,nx ,ny) FILE *fp; u_char **array; int nx,ny; { long rsize; rsize = nx * ny; if (Fread(array[0], sizeof(u_char), rsize, fp) != rsize) { perror("\n error reading file\n"); return (-1); } return(0); } /*******************************/ int write_3d_byte_array(fp,array,nx,ny,nz) FILE *fp; u_char ***array; int nx,ny,nz; { long size; size = nx * ny * nz; if (Fwrite(array[0][0], sizeof(u_char), size, fp) != size) { perror("\n error writing file\n"); return (-1); } return(0); } /********************************/ int write_2d_byte_array(fp,array,nx ,ny) FILE *fp; u_char **array; int nx,ny; { long size; size = nx* ny; if (Fwrite(array[0], sizeof(u_char), size, fp) != size) { perror("\n error writing file\n"); return(-1); } return(0); } /********************************/ void free_3d_byte_array(array) u_char ***array; { free((char *)array[0][0]); free((char *)array[0]); free((char *)array); } /*********************************/ void free_2d_byte_array(array) u_char **array; { free((char *)array[0]); free((char *)array); } /********************************************************/ /* same routines for data type short */ /********************************************************/ short *** alloc_3d_short_array(nx,ny,nz) int nx,ny,nz; { short ***array; register int i, j; /* allocate 3-d array for input image data */ /* allocate 2 arrays of pointers */ if ((array = Calloc(nx, short **)) == NULL) perror("calloc error: array "); if ((array[0] = Calloc(nx * ny, short *)) == NULL) perror("calloc error: array "); /* allocate array for data */ if ((array[0][0] = Calloc(nx * ny * nz, short)) == NULL) perror("calloc error: array "); /* initialize pointer arrays */ for (i = 1; i < ny; i++) array[0][i] = **array + (nz * i); for (i = 1; i < nx; i++) { array[i] = *array + (ny * i); array[i][0] = **array + (ny * nz * i); for (j = 1; j < ny; j++)/* initialize pointer array */ array[i][j] = array[i][0] + (nz * j); } return(array); } /**********************************/ short ** alloc_2d_short_array(nx,ny) int nx,ny; { short **array; register int i; /* allocate 2-d array for input image data */ /* allocate array of pointers */ if ((array = Calloc(nx, short *)) == NULL) perror("calloc error: array "); /* allocate array for data */ if ((array[0] = Calloc(nx * ny, short)) == NULL) perror("calloc error: array "); /* initialize pointer arrays */ for (i = 0; i < nx; i++) array[i] = *array + (ny * i); return(array); } /********************************/ int read_3d_short_array(fp,array,nx,ny,nz) FILE *fp; short ***array; int nx,ny,nz; { long rsize; rsize = nx * ny * nz; if (Fread(array[0][0], sizeof(short), rsize, fp) != rsize) { perror("\n error reading file\n"); return(-1); } return(0); } /********************************/ int read_2d_short_array(fp,array,nx ,ny) FILE *fp; short **array; int nx,ny; { long rsize; rsize = nx * ny; if (Fread(array[0], sizeof(short), rsize, fp) != rsize) { perror("\n error reading file\n"); return(-1); } return(0); } /*******************************/ int write_3d_short_array(fp,array,nx,ny,nz) FILE *fp; short ***array; int nx,ny,nz; { long size; size = nx * ny * nz; if (Fwrite(array[0][0], sizeof(short), size, fp) != size) { perror("\n error writing file\n"); return(-1); } return(0); } /********************************/ int write_2d_short_array(fp,array,nx ,ny) FILE *fp; short **array; int nx,ny; { long size; size = nx* ny; if (Fwrite(array[0], sizeof(short), size, fp) != size) { perror("\n error writing file\n"); return(-1); } return(0); } /********************************/ void free_3d_short_array(array) short ***array; { free((char *)array[0][0]); free((char *)array[0]); free((char *)array); } /*********************************/ void free_2d_short_array(array) short **array; { free((char *)array[0]); free((char *)array); } /****************************************************/ /* int routines */ /**************************************************/ int *** alloc_3d_int_array(nx,ny,nz) int nx,ny,nz; { int ***array; register int i, j; /* allocate 3-d array for input image data */ /* allocate 2 arrays of pointers */ if ((array = Calloc(nx, int **)) == NULL) perror("calloc error: array "); if ((array[0] = Calloc(nx * ny, int *)) == NULL) perror("calloc error: array "); /* allocate array for data */ if ((array[0][0] = Calloc(nx * ny * nz, int)) == NULL) perror("calloc error: array "); /* initialize pointer arrays */ for (i = 1; i < ny; i++) array[0][i] = **array + (nz * i); for (i = 1; i < nx; i++) { array[i] = *array + (ny * i); array[i][0] = **array + (ny * nz * i); for (j = 1; j < ny; j++)/* initialize pointer array */ array[i][j] = array[i][0] + (nz * j); } return(array); } /**********************************/ int ** alloc_2d_int_array(nx,ny) int nx,ny; { int **array; register int i; /* allocate 2-d array for input image data */ /* allocate array of pointers */ if ((array = Calloc(nx, int *)) == NULL) perror("calloc error: array "); /* allocate array for data */ if ((array[0] = Calloc(nx * ny, int)) == NULL) perror("calloc error: array "); /* initialize pointer arrays */ for (i = 0; i < nx; i++) array[i] = *array + (ny * i); return(array); } /********************************/ int read_3d_int_array(fp,array,nx,ny,nz) FILE *fp; int ***array; int nx,ny,nz; { long rsize; rsize = nx * ny * nz; if (Fread(array[0][0], sizeof(int), rsize, fp) != rsize) { perror("\n error reading file\n"); return(-1); } return(0); } /********************************/ int read_2d_int_array(fp,array,nx ,ny) FILE *fp; int **array; int nx,ny; { long rsize; rsize = nx * ny; if (Fread(array[0], sizeof(int), rsize, fp) != rsize) { perror("\n error reading file\n"); return(-1); } return(0); } /*******************************/ int write_3d_int_array(fp,array,nx,ny,nz) FILE *fp; int ***array; int nx,ny,nz; { long size; size = nx * ny * nz; if (Fwrite(array[0][0], sizeof(int), size, fp) != size) { perror("\n error writing file\n"); return(-1); } return(0); } /********************************/ int write_2d_int_array(fp,array,nx ,ny) FILE *fp; int **array; int nx,ny; { long size; size = nx* ny; if (Fwrite(array[0], sizeof(int), size, fp) != size) { perror("\n error writing file\n"); return(-1); } return(0); } /********************************/ void free_3d_int_array(array) int ***array; { free((char *)array[0][0]); free((char *)array[0]); free((char *)array); } /*********************************/ void free_2d_int_array(array) int **array; { free((char *)array[0]); free((char *)array); } /****************************************************/ /* float routines */ /**************************************************/ float *** alloc_3d_float_array(nx,ny,nz) int nx,ny,nz; { float ***array; register int i, j; /* allocate 3-d array for input image data */ /* allocate 2 arrays of pointers */ if ((array = Calloc(nx, float **)) == NULL) perror("calloc error: array "); if ((array[0] = Calloc(nx * ny, float *)) == NULL) perror("calloc error: array "); /* allocate array for data */ if ((array[0][0] = Calloc(nx * ny * nz, float)) == NULL) perror("calloc error: array "); /* initialize pointer arrays */ for (i = 1; i < ny; i++) array[0][i] = **array + (nz * i); for (i = 1; i < nx; i++) { array[i] = *array + (ny * i); array[i][0] = **array + (ny * nz * i); for (j = 1; j < ny; j++)/* initialize pointer array */ array[i][j] = array[i][0] + (nz * j); } return(array); } /**********************************/ float ** alloc_2d_float_array(nx,ny) int nx,ny; { float **array; register int i; /* allocate 2-d array for input image data */ /* allocate array of pointers */ if ((array = Calloc(nx, float *)) == NULL) perror("calloc error: array "); /* allocate array for data */ if ((array[0] = Calloc(nx * ny, float)) == NULL) perror("calloc error: array "); /* initialize pointer arrays */ for (i = 0; i < nx; i++) array[i] = *array + (ny * i); return(array); } /********************************/ int read_3d_float_array(fp,array,nx,ny,nz) FILE *fp; float ***array; int nx,ny,nz; { long rsize; rsize = nx * ny * nz; if (Fread(array[0][0], sizeof(float), rsize, fp) != rsize) { perror("\n error reading file\n"); return(-1); } return(0); } /********************************/ int read_2d_float_array(fp,array,nx ,ny) FILE *fp; float **array; int nx,ny; { long rsize; rsize = nx * ny; if (Fread(array[0], sizeof(float), rsize, fp) != rsize) { perror("\n error reading file\n"); return(-1); } return(0); } /*******************************/ int write_3d_float_array(fp,array,nx,ny,nz) FILE *fp; float ***array; int nx,ny,nz; { long size; size = nx * ny * nz; if (Fwrite(array[0][0], sizeof(float), size, fp) != size) { perror("\n error writing file\n"); return(-1); } return(0); } /********************************/ int write_2d_float_array(fp,array,nx ,ny) FILE *fp; float **array; int nx,ny; { long size; size = nx* ny; if (Fwrite(array[0], sizeof(float), size, fp) != size) { perror("\n error writing file\n"); return(-1); } return(0); } /********************************/ void free_3d_float_array(array) float ***array; { free((char *)array[0][0]); free((char *)array[0]); free((char *)array); } /*********************************/ void free_2d_float_array(array) float **array; { free((char *)array[0]); free((char *)array); } /**************************************************************/ /* long routines */ /**************************************************************/ long *** alloc_3d_long_array(nx,ny,nz) /* in hips terminology: col,row,frame */ int nx,ny,nz; { long ***array; register int i, j; /* allocate 3-d array for input image data */ /* allocate 2 arrays of pointers */ if ((array = Calloc(nx, long **)) == NULL) perror("calloc error: array "); if ((array[0] = Calloc(nx * ny, long *)) == NULL) perror("calloc error: array "); /* allocate array for data */ if ((array[0][0] = Calloc(nx * ny * nz, long)) == NULL) perror("calloc error: array "); /* initialize pointer arrays */ for (i = 1; i < ny; i++) array[0][i] = **array + (nz * i); for (i = 1; i < nx; i++) { array[i] = *array + (ny * i); array[i][0] = **array + (nz * ny * i); for (j = 1; j < ny; j++)/* initialize pointer array */ array[i][j] = array[i][0] + (nz * j); } return(array); } /**********************************/ long ** alloc_2d_long_array(nx,ny) int nx,ny; { long **array; register int i; /* allocate 2-d array for input image data */ /* allocate array of pointers */ if ((array = Calloc(nx, long *)) == NULL) perror("calloc error: array "); /* allocate array for data */ if ((array[0] = Calloc(nx * ny, long)) == NULL) perror("calloc error: array "); /* initialize pointer arrays */ for (i = 0; i < nx; i++) array[i] = *array + (ny * i); return(array); } /********************************/ void free_3d_long_array(array) long ***array; { free((char *)array[0][0]); free((char *)array[0]); free((char *)array); } /*********************************/ void free_2d_long_array(array) long **array; { free((char *)array[0]); free((char *)array); } /***********************************************************************/ /* all types: all use these if array is cast when calling the routine */ /***********************************************************************/ void free_3d_array(array) char ***array; { free(array[0][0]); free(array[0]); free(array); }
the_stack_data/392931.c
#include <stdio.h> #include <stdlib.h> #include <string.h> int wcount(char *s) { long n,i; n = i = 0; n=strlen(s); int count = 1; for (i=0;i<n;i++) { if (i != 0 && i != n-1 && (*(s + i)) == ' ') count+=1; } return count; } int main(int argc, char** argv) { long r,i,j; r = i = j = 0; char s[100000]; gets(s); for (i=0;i<strlen(s);i++) { if (j == 1) break; else { if (s[i] != ' ') { s[j] = s[i]; j=j+1; } } } if (j == 0) s[j]='\0'; if (strlen(s) == 0) { printf ("0"); return 0; } r = wcount (s); printf("%ld", r); return 0; }
the_stack_data/218894484.c
#include <stdio.h> int main() { printf("Yess hello martin\n"); printf("\nAnge ett tal"); return 0; }
the_stack_data/75690.c
/* * Created by gt on 1/28/22 - 12:57 PM. * Copyright (c) 2022 GTXC. All rights reserved. * * A non-empty array A consisting of N integers is given. Array A represents numbers on a tape. * * Any integer P, such that 0 < P < N, splits this tape into two non-empty parts: A[0], A[1], ..., * A[P - 1] and A[P], A[P + 1], ..., A[N - 1]. * * The difference between the two parts is the value of: |(A[0] + A[1] + ... + A[P - 1]) - (A[P] + * A[P + 1] + ... + A[N - 1])| * * In other words, it is the absolute difference between the sum of the first part and the sum of * the second part. * * For example, consider array A such that: * * A[0] = 3 * A[1] = 1 * A[2] = 2 * A[3] = 4 * A[4] = 3 * We can split this tape in four places: * * P = 1, difference = |3 - 10| = 7 * P = 2, difference = |4 - 9| = 5 * P = 3, difference = |6 - 7| = 1 * P = 4, difference = |10 - 3| = 7 * Write a function: * * int solution(int A[], int N); * * that, given a non-empty array A of N integers, returns the minimal difference that can be * achieved. * * For example, given: * * A[0] = 3 * A[1] = 1 * A[2] = 2 * A[3] = 4 * A[4] = 3 * the function should return 1, as explained above. * * Write an efficient algorithm for the following assumptions: * * N is an integer within the range [2..100,000]; * each element of array A is an integer within the range [-1,000..1,000]. * */ #include <stdio.h> #include <stdlib.h> void print_int_array(int arr[], int size) { printf("["); for (int i = 0; i < size; ++i) { if (i == size - 1) printf("%i", arr[i]); else printf("%i, ", arr[i]); } printf("]\n"); } int solution(int A[], int N) { int dif; int min_dif = 2000; int sum[N]; sum[0] = A[0]; for (int i = 1; i < N; ++i) { sum[i] = sum[i-1] + A[i]; } for (int P = 1; P < N; ++P) { dif = abs(sum[N - 1] - sum[P-1] - sum[P-1]); if (min_dif > dif) { min_dif = dif; } if (min_dif == 0) { break; } } return min_dif; } int main() { int A[] = {3, 1, 2, 4, 3}; int size = sizeof A / sizeof A[0]; printf("min difference: %i\n", solution(A, size)); return 0; }
the_stack_data/165769579.c
#include <stdint.h> char * v = (char*)0xB8000 + 79 * 2; extern char bss; extern char endOfBinary; static int var1 = 0; static int var2 = 0; void * memset(void * destiny, int32_t c, uint64_t length); int main() { //Clean BSS memset(&bss, 0, &endOfBinary - &bss); //All the following code may be removed *v = 'X'; //Test if BSS is properly set up if (var1 == 0 && var2 == 0) return 0x42; //0xDEADC0DE; return 0xDEADBEEF; } void * memset(void * destiation, int32_t c, uint64_t length) { uint8_t chr = (uint8_t)c; char * dst = (char*)destiation; while(length--) dst[length] = chr; return destiation; }
the_stack_data/67324147.c
struct S { int (*fptr)(); }; int foo() { return 0; } int main() { struct S v; v.fptr = foo; return v.fptr(); }
the_stack_data/876139.c
#include <yaml.h> #include <stdlib.h> #include <stdio.h> #include <assert.h> void print_escaped(yaml_char_t * str, size_t length); int usage(int ret); int main(int argc, char *argv[]) { FILE *input; yaml_parser_t parser; yaml_event_t event; int flow = -1; /** default no flow style collections */ int i = 0; int foundfile = 0; for (i = 1; i < argc; i++) { if (strncmp(argv[i], "--flow", 6) == 0) { if (i+1 == argc) return usage(1); i++; if (strncmp(argv[i], "keep", 4) == 0) flow = 0; else if (strncmp(argv[i], "on", 2) == 0) flow = 1; else if (strncmp(argv[i], "off", 3) == 0) flow = -1; else return usage(1); } else if (strncmp(argv[i], "--help", 6) == 0) return usage(0); else if (strncmp(argv[i], "-h", 2) == 0) return usage(0); else if (!foundfile) { input = fopen(argv[i], "rb"); foundfile = 1; } else return usage(1); } if (!foundfile) { input = stdin; } assert(input); if (!yaml_parser_initialize(&parser)) { fprintf(stderr, "Could not initialize the parser object\n"); return 1; } yaml_parser_set_input_file(&parser, input); while (1) { yaml_event_type_t type; if (!yaml_parser_parse(&parser, &event)) { if ( parser.problem_mark.line || parser.problem_mark.column ) { fprintf(stderr, "Parse error: %s\nLine: %lu Column: %lu\n", parser.problem, (unsigned long)parser.problem_mark.line + 1, (unsigned long)parser.problem_mark.column + 1); } else { fprintf(stderr, "Parse error: %s\n", parser.problem); } return 1; } type = event.type; if (type == YAML_NO_EVENT) printf("???\n"); else if (type == YAML_STREAM_START_EVENT) printf("+STR\n"); else if (type == YAML_STREAM_END_EVENT) printf("-STR\n"); else if (type == YAML_DOCUMENT_START_EVENT) { printf("+DOC"); if (!event.data.document_start.implicit) printf(" ---"); printf("\n"); } else if (type == YAML_DOCUMENT_END_EVENT) { printf("-DOC"); if (!event.data.document_end.implicit) printf(" ..."); printf("\n"); } else if (type == YAML_MAPPING_START_EVENT) { printf("+MAP"); if (flow == 0 && event.data.mapping_start.style == YAML_FLOW_MAPPING_STYLE) printf(" {}"); else if (flow == 1) printf(" {}"); if (event.data.mapping_start.anchor) printf(" &%s", event.data.mapping_start.anchor); if (event.data.mapping_start.tag) printf(" <%s>", event.data.mapping_start.tag); printf("\n"); } else if (type == YAML_MAPPING_END_EVENT) printf("-MAP\n"); else if (type == YAML_SEQUENCE_START_EVENT) { printf("+SEQ"); if (flow == 0 && event.data.sequence_start.style == YAML_FLOW_SEQUENCE_STYLE) printf(" []"); else if (flow == 1) printf(" []"); if (event.data.sequence_start.anchor) printf(" &%s", event.data.sequence_start.anchor); if (event.data.sequence_start.tag) printf(" <%s>", event.data.sequence_start.tag); printf("\n"); } else if (type == YAML_SEQUENCE_END_EVENT) printf("-SEQ\n"); else if (type == YAML_SCALAR_EVENT) { printf("=VAL"); if (event.data.scalar.anchor) printf(" &%s", event.data.scalar.anchor); if (event.data.scalar.tag) printf(" <%s>", event.data.scalar.tag); switch (event.data.scalar.style) { case YAML_PLAIN_SCALAR_STYLE: printf(" :"); break; case YAML_SINGLE_QUOTED_SCALAR_STYLE: printf(" '"); break; case YAML_DOUBLE_QUOTED_SCALAR_STYLE: printf(" \""); break; case YAML_LITERAL_SCALAR_STYLE: printf(" |"); break; case YAML_FOLDED_SCALAR_STYLE: printf(" >"); break; case YAML_ANY_SCALAR_STYLE: abort(); } print_escaped(event.data.scalar.value, event.data.scalar.length); printf("\n"); } else if (type == YAML_ALIAS_EVENT) printf("=ALI *%s\n", event.data.alias.anchor); else abort(); yaml_event_delete(&event); if (type == YAML_STREAM_END_EVENT) break; } assert(!fclose(input)); yaml_parser_delete(&parser); fflush(stdout); return 0; } void print_escaped(yaml_char_t * str, size_t length) { int i; char c; for (i = 0; i < length; i++) { c = *(str + i); if (c == '\\') printf("\\\\"); else if (c == '\0') printf("\\0"); else if (c == '\b') printf("\\b"); else if (c == '\n') printf("\\n"); else if (c == '\r') printf("\\r"); else if (c == '\t') printf("\\t"); else printf("%c", c); } } int usage(int ret) { fprintf(stderr, "Usage: libyaml-parser [--flow (on|off|keep)] [<input-file>]\n"); return ret; }
the_stack_data/916886.c
/* DataToC output of file <workbench_prepass_frag_glsl> */ extern int datatoc_workbench_prepass_frag_glsl_size; extern char datatoc_workbench_prepass_frag_glsl[]; int datatoc_workbench_prepass_frag_glsl_size = 1964; char datatoc_workbench_prepass_frag_glsl[] = { 117,110,105,102,111,114,109, 32,105,110,116, 32,111, 98,106,101, 99,116, 95,105,100, 32, 61, 32, 48, 59, 13, 10, 13, 10,117,110,105,102,111,114,109, 32,118,101, 99, 51, 32,109, 97,116,101,114,105, 97,108, 68,105,102,102,117,115,101, 67,111,108,111,114, 59, 13, 10,117,110,105,102,111,114,109, 32,102,108,111, 97,116, 32,109, 97,116,101,114,105, 97,108, 77,101,116, 97,108,108,105, 99, 59, 13, 10,117,110,105,102,111,114,109, 32,102,108,111, 97,116, 32,109, 97,116,101,114,105, 97,108, 82,111,117,103,104,110,101,115,115, 59, 13, 10, 13, 10,117,110,105,102,111,114,109, 32,115, 97,109,112,108,101,114, 50, 68, 32,105,109, 97,103,101, 59, 13, 10,117,110,105,102,111,114,109, 32,102,108,111, 97,116, 32, 73,109, 97,103,101, 84,114, 97,110,115,112, 97,114,101,110, 99,121, 67,117,116,111,102,102, 32, 61, 32, 48, 46, 49, 59, 13, 10,117,110,105,102,111,114,109, 32, 98,111,111,108, 32,105,109, 97,103,101, 83,114,103, 98, 59, 13, 10,117,110,105,102,111,114,109, 32, 98,111,111,108, 32,105,109, 97,103,101, 78,101, 97,114,101,115,116, 59, 13, 10, 13, 10, 35,105,102,100,101,102, 32, 78, 79, 82, 77, 65, 76, 95, 86, 73, 69, 87, 80, 79, 82, 84, 95, 80, 65, 83, 83, 95, 69, 78, 65, 66, 76, 69, 68, 13, 10,105,110, 32,118,101, 99, 51, 32,110,111,114,109, 97,108, 95,118,105,101,119,112,111,114,116, 59, 13, 10, 35,101,110,100,105,102, 13, 10, 13, 10, 35,105,102,100,101,102, 32, 86, 51, 68, 95, 83, 72, 65, 68, 73, 78, 71, 95, 84, 69, 88, 84, 85, 82, 69, 95, 67, 79, 76, 79, 82, 13, 10,105,110, 32,118,101, 99, 50, 32,117,118, 95,105,110,116,101,114,112, 59, 13, 10, 35,101,110,100,105,102, 13, 10, 13, 10, 35,105,102,100,101,102, 32, 72, 65, 73, 82, 95, 83, 72, 65, 68, 69, 82, 13, 10,102,108, 97,116, 32,105,110, 32,102,108,111, 97,116, 32,104, 97,105,114, 95,114, 97,110,100, 59, 13, 10, 35,101,110,100,105,102, 13, 10, 13, 10, 35,105,102,100,101,102, 32, 77, 65, 84, 68, 65, 84, 65, 95, 80, 65, 83, 83, 95, 69, 78, 65, 66, 76, 69, 68, 13, 10,108, 97,121,111,117,116, 40,108,111, 99, 97,116,105,111,110, 61, 48, 41, 32,111,117,116, 32,118,101, 99, 52, 32,109, 97,116,101,114,105, 97,108, 68, 97,116, 97, 59, 13, 10, 35,101,110,100,105,102, 13, 10, 35,105,102,100,101,102, 32, 79, 66, 74, 69, 67, 84, 95, 73, 68, 95, 80, 65, 83, 83, 95, 69, 78, 65, 66, 76, 69, 68, 13, 10,108, 97,121,111,117,116, 40,108,111, 99, 97,116,105,111,110, 61, 49, 41, 32,111,117,116, 32,117,105,110,116, 32,111, 98,106,101, 99,116, 73,100, 59, 13, 10, 35,101,110,100,105,102, 13, 10, 35,105,102,100,101,102, 32, 78, 79, 82, 77, 65, 76, 95, 86, 73, 69, 87, 80, 79, 82, 84, 95, 80, 65, 83, 83, 95, 69, 78, 65, 66, 76, 69, 68, 13, 10,108, 97,121,111,117,116, 40,108,111, 99, 97,116,105,111,110, 61, 50, 41, 32,111,117,116, 32, 87, 66, 95, 78,111,114,109, 97,108, 32,110,111,114,109, 97,108, 86,105,101,119,112,111,114,116, 59, 13, 10, 35,101,110,100,105,102, 13, 10, 13, 10,118,111,105,100, 32,109, 97,105,110, 40, 41, 13, 10,123, 13, 10, 35,105,102,100,101,102, 32, 77, 65, 84, 68, 65, 84, 65, 95, 80, 65, 83, 83, 95, 69, 78, 65, 66, 76, 69, 68, 13, 10, 9,102,108,111, 97,116, 32,109,101,116, 97,108,108,105, 99, 44, 32,114,111,117,103,104,110,101,115,115, 59, 13, 10, 9,118,101, 99, 52, 32, 99,111,108,111,114, 59, 13, 10, 13, 10, 35, 32, 32,105,102,100,101,102, 32, 86, 51, 68, 95, 83, 72, 65, 68, 73, 78, 71, 95, 84, 69, 88, 84, 85, 82, 69, 95, 67, 79, 76, 79, 82, 13, 10, 9, 99,111,108,111,114, 32, 61, 32,119,111,114,107, 98,101,110, 99,104, 95,115, 97,109,112,108,101, 95,116,101,120,116,117,114,101, 40,105,109, 97,103,101, 44, 32,117,118, 95,105,110,116,101,114,112, 44, 32,105,109, 97,103,101, 83,114,103, 98, 44, 32,105,109, 97,103,101, 78,101, 97,114,101,115,116, 41, 59, 13, 10, 9,105,102, 32, 40, 99,111,108,111,114, 46, 97, 32, 60, 32, 73,109, 97,103,101, 84,114, 97,110,115,112, 97,114,101,110, 99,121, 67,117,116,111,102,102, 41, 32,123, 13, 10, 9, 9,100,105,115, 99, 97,114,100, 59, 13, 10, 9,125, 13, 10, 35, 32, 32,101,108,115,101, 13, 10, 9, 99,111,108,111,114, 46,114,103, 98, 32, 61, 32,109, 97,116,101,114,105, 97,108, 68,105,102,102,117,115,101, 67,111,108,111,114, 59, 13, 10, 35, 32, 32,101,110,100,105,102, 13, 10, 13, 10, 35, 32, 32,105,102,100,101,102, 32, 86, 51, 68, 95, 76, 73, 71, 72, 84, 73, 78, 71, 95, 77, 65, 84, 67, 65, 80, 13, 10, 9, 47, 42, 32, 69,110, 99,111,100,101, 32,102,114,111,110,116, 32,102, 97, 99,105,110,103, 32,105,110, 32,109,101,116, 97,108,108,105, 99, 32, 99,104, 97,110,110,101,108, 46, 32, 42, 47, 13, 10, 9,109,101,116, 97,108,108,105, 99, 32, 61, 32,102,108,111, 97,116, 40,103,108, 95, 70,114,111,110,116, 70, 97, 99,105,110,103, 41, 59, 13, 10, 9,114,111,117,103,104,110,101,115,115, 32, 61, 32, 48, 46, 48, 59, 13, 10, 35, 32, 32,101,108,115,101, 13, 10, 9,109,101,116, 97,108,108,105, 99, 32, 61, 32,109, 97,116,101,114,105, 97,108, 77,101,116, 97,108,108,105, 99, 59, 13, 10, 9,114,111,117,103,104,110,101,115,115, 32, 61, 32,109, 97,116,101,114,105, 97,108, 82,111,117,103,104,110,101,115,115, 59, 13, 10, 35, 32, 32,101,110,100,105,102, 13, 10, 13, 10, 35, 32, 32,105,102,100,101,102, 32, 72, 65, 73, 82, 95, 83, 72, 65, 68, 69, 82, 13, 10, 9, 47, 42, 32, 65,100,100, 32,115,111,109,101, 32,118, 97,114,105, 97,116,105,111,110, 32,116,111, 32,116,104,101, 32,104, 97,105,114,115, 32,116,111, 32, 97,118,111,105,100, 32,117,110,105,102,111,114,109, 32,108,111,111,107, 46, 32, 42, 47, 13, 10, 9,102,108,111, 97,116, 32,104, 97,105,114, 95,118, 97,114,105, 97,116,105,111,110, 32, 61, 32,104, 97,105,114, 95,114, 97,110,100, 32, 42, 32, 48, 46, 49, 59, 13, 10, 9, 99,111,108,111,114, 32, 61, 32, 99,108, 97,109,112, 40, 99,111,108,111,114, 32, 45, 32,104, 97,105,114, 95,118, 97,114,105, 97,116,105,111,110, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 13, 10, 9,109,101,116, 97,108,108,105, 99, 32, 61, 32, 99,108, 97,109,112, 40,109, 97,116,101,114,105, 97,108, 77,101,116, 97,108,108,105, 99, 32, 45, 32,104, 97,105,114, 95,118, 97,114,105, 97,116,105,111,110, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 13, 10, 9,114,111,117,103,104,110,101,115,115, 32, 61, 32, 99,108, 97,109,112, 40,109, 97,116,101,114,105, 97,108, 82,111,117,103,104,110,101,115,115, 32, 45, 32,104, 97,105,114, 95,118, 97,114,105, 97,116,105,111,110, 44, 32, 48, 46, 48, 44, 32, 49, 46, 48, 41, 59, 13, 10, 35, 32, 32,101,110,100,105,102, 13, 10, 13, 10, 9,109, 97,116,101,114,105, 97,108, 68, 97,116, 97, 46,114,103, 98, 32, 61, 32, 99,111,108,111,114, 46,114,103, 98, 59, 13, 10, 9,109, 97,116,101,114,105, 97,108, 68, 97,116, 97, 46, 97, 32, 32, 32, 61, 32,119,111,114,107, 98,101,110, 99,104, 95,102,108,111, 97,116, 95,112, 97,105,114, 95,101,110, 99,111,100,101, 40,114,111,117,103,104,110,101,115,115, 44, 32,109,101,116, 97,108,108,105, 99, 41, 59, 13, 10, 35,101,110,100,105,102, 32, 47, 42, 32, 77, 65, 84, 68, 65, 84, 65, 95, 80, 65, 83, 83, 95, 69, 78, 65, 66, 76, 69, 68, 32, 42, 47, 13, 10, 13, 10, 35,105,102,100,101,102, 32, 79, 66, 74, 69, 67, 84, 95, 73, 68, 95, 80, 65, 83, 83, 95, 69, 78, 65, 66, 76, 69, 68, 13, 10, 9,111, 98,106,101, 99,116, 73,100, 32, 61, 32,117,105,110,116, 40,111, 98,106,101, 99,116, 95,105,100, 41, 59, 13, 10, 35,101,110,100,105,102, 13, 10, 13, 10, 35,105,102,100,101,102, 32, 78, 79, 82, 77, 65, 76, 95, 86, 73, 69, 87, 80, 79, 82, 84, 95, 80, 65, 83, 83, 95, 69, 78, 65, 66, 76, 69, 68, 13, 10, 9,118,101, 99, 51, 32,110, 32, 61, 32, 40,103,108, 95, 70,114,111,110,116, 70, 97, 99,105,110,103, 41, 32, 63, 32,110,111,114,109, 97,108, 95,118,105,101,119,112,111,114,116, 32, 58, 32, 45,110,111,114,109, 97,108, 95,118,105,101,119,112,111,114,116, 59, 13, 10, 9,110, 32, 61, 32,110,111,114,109, 97,108,105,122,101, 40,110, 41, 59, 13, 10, 9,110,111,114,109, 97,108, 86,105,101,119,112,111,114,116, 32, 61, 32,119,111,114,107, 98,101,110, 99,104, 95,110,111,114,109, 97,108, 95,101,110, 99,111,100,101, 40,110, 41, 59, 13, 10, 35,101,110,100,105,102, 13, 10,125, 13, 10,0 };
the_stack_data/24950.c
/* * C Program to Create Employee Record and Update it */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define size 200 struct emp { int id; char *name; }*emp1, *emp3; void display(); void create(); void update(); FILE *fp, *fp1; int count = 0; void main(int argc, char **argv) { int i, n, ch; printf("1] Create a Record\n"); printf("2] Display Records\n"); printf("3] Update Records\n"); printf("4] Exit"); while (1) { printf("\nEnter your choice : "); scanf("%d", &ch); switch (ch) { case 1: fp = fopen(argv[1], "a"); create(); break; case 2: fp1 = fopen(argv[1],"rb"); display(); break; case 3: fp1 = fopen(argv[1], "r+"); update(); break; case 4: exit(0); } } } /* To create an employee record */ void create() { int i; char *p; emp1 = (struct emp *)malloc(sizeof(struct emp)); emp1->name = (char *)malloc((size)*(sizeof(char))); printf("Enter name of employee : "); scanf(" %[^\n]s", emp1->name); printf("Enter emp id : "); scanf(" %d", &emp1->id); fwrite(&emp1->id, sizeof(emp1->id), 1, fp); fwrite(emp1->name, size, 1, fp); count++; // count to number of entries of records fclose(fp); } /* Display the records in the file */ void display() { emp3=(struct emp *)malloc(1*sizeof(struct emp)); emp3->name=(char *)malloc(size*sizeof(char)); int i = 1; if (fp1 == NULL) printf("\nFile not opened for reading"); while (i <= count) { fread(&emp3->id, sizeof(emp3->id), 1, fp1); fread(emp3->name, size, 1, fp1); printf("\n%d %s",emp3->id,emp3->name); i++; } fclose(fp1); free(emp3->name); free(emp3); } void update() { int id, flag = 0, i = 1; char s[size]; if (fp1 == NULL) { printf("File cant be opened"); return; } printf("Enter employee id to update : "); scanf("%d", &id); emp3 = (struct emp *)malloc(1*sizeof(struct emp)); emp3->name=(char *)malloc(size*sizeof(char)); while(i<=count) { fread(&emp3->id, sizeof(emp3->id), 1, fp1); fread(emp3->name,size,1,fp1); if (id == emp3->id) { printf("Enter new name of emplyee to update : "); scanf(" %[^\n]s", s); fseek(fp1, -204L, SEEK_CUR); fwrite(&emp3->id, sizeof(emp3->id), 1, fp1); fwrite(s, size, 1, fp1); flag = 1; break; } i++; } if (flag != 1) { printf("No employee record found"); flag = 0; } fclose(fp1); free(emp3->name); /* to free allocated memory */ free(emp3); }
the_stack_data/61076154.c
/* Copyright (C) 1992, 1996, 1997 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #if !defined (WIN32) #include <termios.h> /* Set *T to indicate raw mode. */ void cfmakeraw (t) struct termios *t; { t->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON); t->c_oflag &= ~OPOST; t->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN); t->c_cflag &= ~(CSIZE|PARENB); t->c_cflag |= CS8; t->c_cc[VMIN] = 1; /* read returns when one char is available. */ t->c_cc[VTIME] = 0; } #endif
the_stack_data/1218287.c
#include "stdio.h" int main() { float f; double d; printf("Insert a double number.\n"); scanf("%lf", &d); f = (float)d; printf("%0.12f\n",d); printf("%0.12f\n",f); return 0; }
the_stack_data/153268740.c
/* powlong.c: Computes x**y where x and y are 32-bit longs. Copyright (C) 2006 Ralph Hempel This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* Version 1.0 - Initial release */ long powlong(long x, long y) { long res = x; if(y == 0.0) return 1.0; if(y == 1.0) return res; if(x <= 0.0) return 0.0; while( --y ) res *= x; return( res ); }
the_stack_data/248581237.c
/** * Copyright 2020 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef ENABLE_SSE #include <x86intrin.h> #include "nnacl/fp32/conv_depthwise_fp32.h" void ConvDwFp32Border(float *dst, const float *src, const float *weight, const float *bias, size_t height, size_t width, size_t in_kh_step, size_t in_kw_step, size_t kernel_w_step, size_t relu, size_t relu6) { in_kh_step /= sizeof(float); in_kw_step /= sizeof(float); kernel_w_step /= sizeof(float); const float *src_kh = src; const float *weight_kh = weight; __m128 dst_ma = _mm_setzero_ps(); for (int kh = 0; kh < height; kh++) { const float *src_kw = src_kh; const float *weight_kw = weight_kh; int c1 = 0; int c4 = DOWN_DIV(width, C4NUM) * C4NUM; int c2 = DOWN_DIV(width, C2NUM) * C2NUM; // c4 loop for (; c1 < c4; c1 += C4NUM) { __m128 src_ma1 = _mm_loadu_ps(src_kw); __m128 src_ma2 = _mm_loadu_ps(src_kw + in_kw_step); __m128 src_ma3 = _mm_loadu_ps(src_kw + 2 * in_kw_step); __m128 src_ma4 = _mm_loadu_ps(src_kw + 3 * in_kw_step); __m128 weight_ma1 = _mm_loadu_ps(weight_kw); __m128 weight_ma2 = _mm_loadu_ps(weight_kw + C4NUM); __m128 weight_ma3 = _mm_loadu_ps(weight_kw + 2 * C4NUM); __m128 weight_ma4 = _mm_loadu_ps(weight_kw + 3 * C4NUM); __m128 mul_ma1 = _mm_mul_ps(src_ma1, weight_ma1); __m128 mul_ma2 = _mm_mul_ps(src_ma2, weight_ma2); __m128 mul_ma3 = _mm_mul_ps(src_ma3, weight_ma3); __m128 mul_ma4 = _mm_mul_ps(src_ma4, weight_ma4); dst_ma = _mm_add_ps(dst_ma, mul_ma1); dst_ma = _mm_add_ps(dst_ma, mul_ma2); dst_ma = _mm_add_ps(dst_ma, mul_ma3); dst_ma = _mm_add_ps(dst_ma, mul_ma4); src_kw += in_kw_step * 4; weight_kw += C4NUM * 4; } // c2 loop for (; c1 < c2; c1 += C2NUM) { __m128 src_ma1 = _mm_loadu_ps(src_kw); __m128 src_ma2 = _mm_loadu_ps(src_kw + in_kw_step); __m128 weight_ma1 = _mm_loadu_ps(weight_kw); __m128 weight_ma2 = _mm_loadu_ps(weight_kw + C4NUM); __m128 mul_ma1 = _mm_mul_ps(src_ma1, weight_ma1); __m128 mul_ma2 = _mm_mul_ps(src_ma2, weight_ma2); dst_ma = _mm_add_ps(dst_ma, mul_ma1); dst_ma = _mm_add_ps(dst_ma, mul_ma2); src_kw += in_kw_step * 2; weight_kw += C4NUM * 2; } // remaining for (; c1 < width; ++c1) { __m128 src_ma1 = _mm_loadu_ps(src_kw); __m128 weight_ma1 = _mm_loadu_ps(weight_kw); __m128 mul_ma1 = _mm_mul_ps(src_ma1, weight_ma1); dst_ma = _mm_add_ps(dst_ma, mul_ma1); src_kw += in_kw_step; weight_kw += C4NUM; } src_kh += in_kh_step; weight_kh += kernel_w_step; } __m128 bias_ma = _mm_loadu_ps(bias); dst_ma = _mm_add_ps(dst_ma, bias_ma); __m128 zero_ma = _mm_setzero_ps(); if (relu || relu6) { dst_ma = _mm_max_ps(zero_ma, dst_ma); if (relu6) { __m128 const_ma = _mm_set_ps(6.0f, 6.0f, 6.0f, 6.0f); dst_ma = _mm_min_ps(const_ma, dst_ma); } } _mm_storeu_ps(dst, dst_ma); } void ConvDwFp32Center(float *dst, const float *src, const float *weight, const float *bias, size_t height, size_t width, size_t kernel_h, size_t kernel_w, size_t out_h_step, size_t block_channel, size_t in_sh_step, size_t in_sw_step, size_t in_kh_step, size_t in_kw_step, size_t relu, size_t relu6) { out_h_step /= sizeof(float); block_channel /= sizeof(float); in_sh_step /= sizeof(float); in_sw_step /= sizeof(float); in_kh_step /= sizeof(float); in_kw_step /= sizeof(float); float *dst_h = dst; const float *src_h = src; for (int oh = 0; oh < height; oh++) { float *dst_w = dst_h; const float *src_w = src_h; int c4 = DOWN_DIV(width, C4NUM) * C4NUM; int c2 = DOWN_DIV(width, C2NUM) * C2NUM; int c1 = 0; // c4 loop for (; c1 < c4; c1 += C4NUM) { const float *src_kh = src_w; const float *weight_kh = weight; __m128 dst_w_ma1 = _mm_setzero_ps(); __m128 dst_w_ma2 = _mm_setzero_ps(); __m128 dst_w_ma3 = _mm_setzero_ps(); __m128 dst_w_ma4 = _mm_setzero_ps(); for (int kh = 0; kh < kernel_h; kh++) { const float *src_kw = src_kh; const float *weight_kw = weight_kh; for (int kw = 0; kw < kernel_w; kw++) { __m128 src_kw_ma1 = _mm_loadu_ps(src_kw); __m128 weight_kw_ma1 = _mm_loadu_ps(weight_kw); __m128 tmp_ma1 = _mm_mul_ps(src_kw_ma1, weight_kw_ma1); dst_w_ma1 = _mm_add_ps(dst_w_ma1, tmp_ma1); __m128 src_kw_ma2 = _mm_loadu_ps(src_kw + in_sw_step); __m128 weight_kw_ma2 = _mm_loadu_ps(weight_kw); __m128 tmp_ma2 = _mm_mul_ps(src_kw_ma2, weight_kw_ma2); dst_w_ma2 = _mm_add_ps(dst_w_ma2, tmp_ma2); __m128 src_kw_ma3 = _mm_loadu_ps(src_kw + 2 * in_sw_step); __m128 weight_kw_ma3 = _mm_loadu_ps(weight_kw); __m128 tmp_ma3 = _mm_mul_ps(src_kw_ma3, weight_kw_ma3); dst_w_ma3 = _mm_add_ps(dst_w_ma3, tmp_ma3); __m128 src_kw_ma4 = _mm_loadu_ps(src_kw + 3 * in_sw_step); __m128 weight_kw_ma4 = _mm_loadu_ps(weight_kw); __m128 tmp_ma4 = _mm_mul_ps(src_kw_ma4, weight_kw_ma4); dst_w_ma4 = _mm_add_ps(dst_w_ma4, tmp_ma4); src_kw += in_kw_step; weight_kw += C4NUM; } // kernel_w loop src_kh += in_kh_step; weight_kh += kernel_w * C4NUM; } // kernel_h loop // add bias relu __m128 bias_ma = _mm_loadu_ps(bias); dst_w_ma1 = _mm_add_ps(dst_w_ma1, bias_ma); dst_w_ma2 = _mm_add_ps(dst_w_ma2, bias_ma); dst_w_ma3 = _mm_add_ps(dst_w_ma3, bias_ma); dst_w_ma4 = _mm_add_ps(dst_w_ma4, bias_ma); __m128 zero_ma = _mm_setzero_ps(); if (relu || relu6) { dst_w_ma1 = _mm_max_ps(zero_ma, dst_w_ma1); dst_w_ma2 = _mm_max_ps(zero_ma, dst_w_ma2); dst_w_ma3 = _mm_max_ps(zero_ma, dst_w_ma3); dst_w_ma4 = _mm_max_ps(zero_ma, dst_w_ma4); if (relu6) { __m128 const_ma = _mm_set_ps(6.0f, 6.0f, 6.0f, 6.0f); dst_w_ma1 = _mm_min_ps(const_ma, dst_w_ma1); dst_w_ma2 = _mm_min_ps(const_ma, dst_w_ma2); dst_w_ma3 = _mm_min_ps(const_ma, dst_w_ma3); dst_w_ma4 = _mm_min_ps(const_ma, dst_w_ma4); } } _mm_storeu_ps(dst_w, dst_w_ma1); _mm_storeu_ps(dst_w + block_channel, dst_w_ma2); _mm_storeu_ps(dst_w + 2 * block_channel, dst_w_ma3); _mm_storeu_ps(dst_w + 3 * block_channel, dst_w_ma4); dst_w += C4NUM * block_channel; src_w += C4NUM * in_sw_step; } // dst_width loop // c2 loop for (; c1 < c2; c1 += C2NUM) { const float *src_kh = src_w; const float *weight_kh = weight; __m128 dst_w_ma1 = _mm_setzero_ps(); __m128 dst_w_ma2 = _mm_setzero_ps(); for (int kh = 0; kh < kernel_h; kh++) { const float *src_kw = src_kh; const float *weight_kw = weight_kh; for (int kw = 0; kw < kernel_w; kw++) { __m128 src_kw_ma1 = _mm_loadu_ps(src_kw); __m128 weight_kw_ma1 = _mm_loadu_ps(weight_kw); __m128 tmp_ma1 = _mm_mul_ps(src_kw_ma1, weight_kw_ma1); dst_w_ma1 = _mm_add_ps(dst_w_ma1, tmp_ma1); __m128 src_kw_ma2 = _mm_loadu_ps(src_kw + in_sw_step); __m128 weight_kw_ma2 = _mm_loadu_ps(weight_kw); __m128 tmp_ma2 = _mm_mul_ps(src_kw_ma2, weight_kw_ma2); dst_w_ma2 = _mm_add_ps(dst_w_ma2, tmp_ma2); src_kw += in_kw_step; weight_kw += C4NUM; } // kernel_w loop src_kh += in_kh_step; weight_kh += kernel_w * C4NUM; } // kernel_h loop // add bias relu __m128 bias_ma = _mm_loadu_ps(bias); dst_w_ma1 = _mm_add_ps(dst_w_ma1, bias_ma); dst_w_ma2 = _mm_add_ps(dst_w_ma2, bias_ma); __m128 zero_ma = _mm_setzero_ps(); if (relu || relu6) { dst_w_ma1 = _mm_max_ps(zero_ma, dst_w_ma1); dst_w_ma2 = _mm_max_ps(zero_ma, dst_w_ma2); if (relu6) { __m128 const_ma = _mm_set_ps(6.0f, 6.0f, 6.0f, 6.0f); dst_w_ma1 = _mm_min_ps(const_ma, dst_w_ma1); dst_w_ma2 = _mm_min_ps(const_ma, dst_w_ma2); } } _mm_storeu_ps(dst_w, dst_w_ma1); _mm_storeu_ps(dst_w + block_channel, dst_w_ma2); dst_w += C2NUM * block_channel; src_w += C2NUM * in_sw_step; } // remaining for (; c1 < width; c1++) { const float *src_kh = src_w; const float *weight_kh = weight; __m128 dst_w_ma1 = _mm_setzero_ps(); for (int kh = 0; kh < kernel_h; kh++) { const float *src_kw = src_kh; const float *weight_kw = weight_kh; for (int kw = 0; kw < kernel_w; kw++) { __m128 src_kw_ma1 = _mm_loadu_ps(src_kw); __m128 weight_kw_ma1 = _mm_loadu_ps(weight_kw); __m128 tmp_ma1 = _mm_mul_ps(src_kw_ma1, weight_kw_ma1); dst_w_ma1 = _mm_add_ps(dst_w_ma1, tmp_ma1); src_kw += in_kw_step; weight_kw += C4NUM; } // kernel_w loop src_kh += in_kh_step; weight_kh += kernel_w * C4NUM; } // kernel_h loop // add bias relu __m128 bias_ma = _mm_loadu_ps(bias); dst_w_ma1 = _mm_add_ps(dst_w_ma1, bias_ma); __m128 zero_ma = _mm_setzero_ps(); if (relu || relu6) { dst_w_ma1 = _mm_max_ps(zero_ma, dst_w_ma1); if (relu6) { __m128 const_ma = _mm_set_ps(6.0f, 6.0f, 6.0f, 6.0f); dst_w_ma1 = _mm_min_ps(const_ma, dst_w_ma1); } } _mm_storeu_ps(dst_w, dst_w_ma1); dst_w += block_channel; src_w += in_sw_step; } dst_h += out_h_step; src_h += in_sh_step; } // dst_height loop } void DeconvDwFp32Center(float *dst, const float *src, const float *weight, size_t height, size_t width, size_t kernel_h, size_t kernel_w, size_t out_h_step, size_t block_channel, size_t in_sh_step, size_t in_sw_step, size_t in_kh_step, size_t in_kw_step) { out_h_step /= sizeof(float); block_channel /= sizeof(float); in_sh_step /= sizeof(float); in_sw_step /= sizeof(float); in_kh_step /= sizeof(float); in_kw_step /= sizeof(float); float *dst_h = dst; const float *src_h = src; for (int oh = 0; oh < height; oh++) { float *dst_w = dst_h; const float *src_w = src_h; for (int ow = 0; ow < width; ow++) { float *dst_kh = dst_w; const float *weight_kh = weight; __m128 src_w_ma = _mm_loadu_ps(src_w); for (int kh = 0; kh < kernel_h; kh++) { float *dst_kw = dst_kh; const float *weight_kw = weight_kh; int c4 = DOWN_DIV(kernel_w, C4NUM) * C4NUM; int c2 = DOWN_DIV(kernel_w, C2NUM) * C2NUM; int c1 = 0; // c4 loop for (; c1 < c4; c1 += C4NUM) { __m128 dst_w_ma1 = _mm_loadu_ps(dst_kw); __m128 weight_kw_ma1 = _mm_loadu_ps(weight_kw); __m128 tmp_ma1 = _mm_mul_ps(src_w_ma, weight_kw_ma1); dst_w_ma1 = _mm_add_ps(dst_w_ma1, tmp_ma1); _mm_storeu_ps(dst_kw, dst_w_ma1); __m128 dst_w_ma2 = _mm_loadu_ps(dst_kw + in_kw_step); __m128 weight_kw_ma2 = _mm_loadu_ps(weight_kw + C4NUM); __m128 tmp_ma2 = _mm_mul_ps(src_w_ma, weight_kw_ma2); dst_w_ma2 = _mm_add_ps(dst_w_ma2, tmp_ma2); _mm_storeu_ps(dst_kw + in_kw_step, dst_w_ma2); __m128 dst_w_ma3 = _mm_loadu_ps(dst_kw + 2 * in_kw_step); __m128 weight_kw_ma3 = _mm_loadu_ps(weight_kw + 2 * C4NUM); __m128 tmp_ma3 = _mm_mul_ps(src_w_ma, weight_kw_ma3); dst_w_ma3 = _mm_add_ps(dst_w_ma3, tmp_ma3); _mm_storeu_ps(dst_kw + 2 * in_kw_step, dst_w_ma3); __m128 dst_w_ma4 = _mm_loadu_ps(dst_kw + 3 * in_kw_step); __m128 weight_kw_ma4 = _mm_loadu_ps(weight_kw + 3 * C4NUM); __m128 tmp_ma4 = _mm_mul_ps(src_w_ma, weight_kw_ma4); dst_w_ma4 = _mm_add_ps(dst_w_ma4, tmp_ma4); _mm_storeu_ps(dst_kw + 3 * in_kw_step, dst_w_ma4); dst_kw += 4 * in_kw_step; weight_kw += 4 * C4NUM; } // c2 loop for (; c1 < c2; c1 += C2NUM) { __m128 dst_w_ma1 = _mm_loadu_ps(dst_kw); __m128 weight_kw_ma1 = _mm_loadu_ps(weight_kw); __m128 tmp_ma1 = _mm_mul_ps(src_w_ma, weight_kw_ma1); dst_w_ma1 = _mm_add_ps(dst_w_ma1, tmp_ma1); _mm_storeu_ps(dst_kw, dst_w_ma1); __m128 dst_w_ma2 = _mm_loadu_ps(dst_kw + in_kw_step); __m128 weight_kw_ma2 = _mm_loadu_ps(weight_kw + C4NUM); __m128 tmp_ma2 = _mm_mul_ps(src_w_ma, weight_kw_ma2); dst_w_ma2 = _mm_add_ps(dst_w_ma2, tmp_ma2); _mm_storeu_ps(dst_kw + in_kw_step, dst_w_ma2); dst_kw += 2 * in_kw_step; weight_kw += 2 * C4NUM; } // remaining for (; c1 < kernel_w; ++c1) { __m128 dst_w_ma1 = _mm_loadu_ps(dst_kw); __m128 weight_kw_ma1 = _mm_loadu_ps(weight_kw); __m128 tmp_ma1 = _mm_mul_ps(src_w_ma, weight_kw_ma1); dst_w_ma1 = _mm_add_ps(dst_w_ma1, tmp_ma1); _mm_storeu_ps(dst_kw, dst_w_ma1); dst_kw += in_kw_step; weight_kw += C4NUM; } // kernel_w loop dst_kh += in_kh_step; weight_kh += kernel_w * C4NUM; } // kernel_h loop dst_w += in_sw_step; src_w += block_channel; } // dst_width loop dst_h += in_sh_step; src_h += out_h_step; } // dst_height loop } #endif
the_stack_data/20450936.c
/* * Testcase to make sure that if we externally reference a versioned symbol * that we always get the right one. */ #include <stdio.h> int foo_1() { return 1034; } int foo_2() { return 1343; } int foo_3() { return 1334; } int main() { printf("Expect 4, get %d\n", foo_1()); printf("Expect 13, get %d\n", foo_2()); printf("Expect 103, get %d\n", foo_3()); return 0; } __asm__(".symver foo_1,show_foo@"); __asm__(".symver foo_2,show_foo@VERS_1.1"); __asm__(".symver foo_3,show_foo@@VERS_1.2");
the_stack_data/147933.c
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_striter.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tmoska <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/11/18 06:50:29 by tmoska #+# #+# */ /* Updated: 2016/11/18 07:10:14 by tmoska ### ########.fr */ /* */ /* ************************************************************************** */ void ft_striter(char *s, void (*f)(char *)) { if (s && (*f)) { while (*s) { (*f)(s); s++; } } }
the_stack_data/26548.c
// // AOJ0583.c // // // Created by n_knuu on 2014/03/31. // // #include <stdio.h> int main(void) { int n,a[3],i,j,k,temp; scanf("%d",&n); for (i=0; i<n; i++) scanf("%d",&a[i]); for (i=0; i<n-1; i++) { if (a[i]<a[i+1]) { temp=a[i]; a[i]=a[i+1]; a[i+1]=temp; } } for (i=1; i<=a[n-1]; i++) { for (j=0; j<n; j++) { if (a[j]%i!=0) break; } if (j==n) printf("%d\n",i); } return 0; }
the_stack_data/932050.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include "../include/asoundlib.h" void show_status(void *handle) { int err; snd_timer_status_t *status; snd_timer_status_alloca(&status); if ((err = snd_timer_status(handle, status)) < 0) { fprintf(stderr, "timer status %i (%s)\n", err, snd_strerror(err)); return; } printf("STATUS:\n"); printf(" resolution = %li\n", snd_timer_status_get_resolution(status)); printf(" lost = %li\n", snd_timer_status_get_lost(status)); printf(" overrun = %li\n", snd_timer_status_get_overrun(status)); printf(" queue = %li\n", snd_timer_status_get_queue(status)); } void read_loop(void *handle, int master_ticks, int timeout) { int count, err; struct pollfd *fds; snd_timer_read_t tr; count = snd_timer_poll_descriptors_count(handle); fds = calloc(count, sizeof(struct pollfd)); if (fds == NULL) { fprintf(stderr, "malloc error\n"); exit(EXIT_FAILURE); } while (master_ticks-- > 0) { if ((err = snd_timer_poll_descriptors(handle, fds, count)) < 0) { fprintf(stderr, "snd_timer_poll_descriptors error: %s\n", snd_strerror(err)); exit(EXIT_FAILURE); } if ((err = poll(fds, count, timeout)) < 0) { fprintf(stderr, "poll error %i (%s)\n", err, strerror(err)); exit(EXIT_FAILURE); } if (err == 0) { fprintf(stderr, "timer time out!!\n"); exit(EXIT_FAILURE); } while (snd_timer_read(handle, &tr, sizeof(tr)) == sizeof(tr)) { printf("TIMER: resolution = %uns, ticks = %u\n", tr.resolution, tr.ticks); } } free(fds); } static void async_callback(snd_async_handler_t *ahandler) { snd_timer_t *handle = snd_async_handler_get_timer(ahandler); int *acount = snd_async_handler_get_callback_private(ahandler); snd_timer_read_t tr; while (snd_timer_read(handle, &tr, sizeof(tr)) == sizeof(tr)) { printf("TIMER: resolution = %uns, ticks = %u\n", tr.resolution, tr.ticks); } (*acount)++; } int main(int argc, char *argv[]) { int idx, err; int class = SND_TIMER_CLASS_GLOBAL; int sclass = SND_TIMER_CLASS_NONE; int card = 0; int device = SND_TIMER_GLOBAL_SYSTEM; int subdevice = 0; int list = 0; int async = 0; int acount = 0; snd_timer_t *handle; snd_timer_id_t *id; snd_timer_info_t *info; snd_timer_params_t *params; char timername[64]; snd_async_handler_t *ahandler; snd_timer_id_alloca(&id); snd_timer_info_alloca(&info); snd_timer_params_alloca(&params); idx = 1; while (idx < argc) { if (!strncmp(argv[idx], "class=", 5)) { class = atoi(argv[idx]+6); } else if (!strncmp(argv[idx], "sclass=", 6)) { sclass = atoi(argv[idx]+7); } else if (!strncmp(argv[idx], "card=", 5)) { card = atoi(argv[idx]+5); } else if (!strncmp(argv[idx], "device=", 7)) { device = atoi(argv[idx]+7); } else if (!strncmp(argv[idx], "subdevice=", 10)) { subdevice = atoi(argv[idx]+10); } else if (!strcmp(argv[idx], "list")) { list = 1; } else if (!strcmp(argv[idx], "async")) { async = 1; } idx++; } if (class == SND_TIMER_CLASS_SLAVE && sclass == SND_TIMER_SCLASS_NONE) { fprintf(stderr, "slave class is not set\n"); exit(EXIT_FAILURE); } if (list) { snd_timer_query_t *qhandle; if ((err = snd_timer_query_open(&qhandle, "hw", 0)) < 0) { fprintf(stderr, "snd_timer_query_open error: %s\n", snd_strerror(err)); exit(EXIT_FAILURE); } snd_timer_id_set_class(id, SND_TIMER_CLASS_NONE); while (1) { if ((err = snd_timer_query_next_device(qhandle, id)) < 0) { fprintf(stderr, "timer next device error: %s\n", snd_strerror(err)); break; } if (snd_timer_id_get_class(id) < 0) break; printf("Timer device: class %i, sclass %i, card %i, device %i, subdevice %i\n", snd_timer_id_get_class(id), snd_timer_id_get_sclass(id), snd_timer_id_get_card(id), snd_timer_id_get_device(id), snd_timer_id_get_subdevice(id)); } snd_timer_query_close(qhandle); exit(EXIT_SUCCESS); } sprintf(timername, "hw:CLASS=%i,SCLASS=%i,CARD=%i,DEV=%i,SUBDEV=%i", class, sclass, card, device, subdevice); if ((err = snd_timer_open(&handle, timername, SND_TIMER_OPEN_NONBLOCK))<0) { fprintf(stderr, "timer open %i (%s)\n", err, snd_strerror(err)); exit(EXIT_FAILURE); } printf("Using timer class %i, slave class %i, card %i, device %i, subdevice %i\n", class, sclass, card, device, subdevice); if ((err = snd_timer_info(handle, info)) < 0) { fprintf(stderr, "timer info %i (%s)\n", err, snd_strerror(err)); exit(0); } printf("Timer info:\n"); printf(" slave = %s\n", snd_timer_info_is_slave(info) ? "yes" : "no"); printf(" card = %i\n", snd_timer_info_get_card(info)); printf(" id = '%s'\n", snd_timer_info_get_id(info)); printf(" name = '%s'\n", snd_timer_info_get_name(info)); printf(" average resolution = %li\n", snd_timer_info_get_resolution(info)); snd_timer_params_set_auto_start(params, 1); if (!snd_timer_info_is_slave(info)) { snd_timer_params_set_ticks(params, (1000000000 / snd_timer_info_get_resolution(info)) / 50); /* 50Hz */ if (snd_timer_params_get_ticks(params) < 1) snd_timer_params_set_ticks(params, 1); printf("Using %li tick(s)\n", snd_timer_params_get_ticks(params)); } else { snd_timer_params_set_ticks(params, 1); } if ((err = snd_timer_params(handle, params)) < 0) { fprintf(stderr, "timer params %i (%s)\n", err, snd_strerror(err)); exit(0); } show_status(handle); if (async) { err = snd_async_add_timer_handler(&ahandler, handle, async_callback, &acount); if (err < 0) { fprintf(stderr, "unable to add async handler %i (%s)\n", err, snd_strerror(err)); exit(EXIT_FAILURE); } } if ((err = snd_timer_start(handle)) < 0) { fprintf(stderr, "timer start %i (%s)\n", err, snd_strerror(err)); exit(EXIT_FAILURE); } if (async) { /* because all other work is done in the signal handler, suspend the process */ while (acount < 25) sleep(1); snd_timer_stop(handle); } else { read_loop(handle, 25, snd_timer_info_is_slave(info) ? 10000 : 25); } show_status(handle); snd_timer_close(handle); printf("Done\n"); return EXIT_SUCCESS; }
the_stack_data/241610.c
//#include <conio.h> #include <stdio.h> #include <stdlib.h> typedef struct { int one, two, five, ten, twenty, fifty, hundred; } banknotes; typedef struct { int fifty, twentyFive, ten, five, one; } coins; int main(void) { banknotes real; coins cents; double purchase, received, moneyChange, storage; system("cls"); // only work in windows OS printf("Purchase value: "); scanf("%lf", &purchase); printf("Received value: "); scanf("%lf", &received); system("cls"); // only work in windows OS if (purchase < received) { purchase = purchase * 100; received = received * 100; moneyChange = received - purchase; storage = moneyChange; real.hundred = 0; real.fifty = 0; real.twenty = 0; real.ten = 0; real.five = 0; real.two = 0; real.one = 0; cents.fifty = 0; cents.twentyFive = 0; cents.ten = 0; cents.five = 0; cents.one = 0; while (moneyChange > 0) { if ((moneyChange >= 1) && (moneyChange < 5)) { cents.one++; moneyChange = moneyChange - 1; } if ((moneyChange >= 5) && (moneyChange < 10)) { cents.five++; moneyChange = moneyChange - 5; } if ((moneyChange >= 10) && (moneyChange < 25)) { cents.ten++; moneyChange = moneyChange - 10; } if ((moneyChange >= 25) && (moneyChange < 50)) { cents.twentyFive++; moneyChange = moneyChange - 25; } if ((moneyChange >= 50) && (moneyChange < 100)) { cents.fifty++; moneyChange = moneyChange - 50; } if ((moneyChange >= (1 * 100)) && (moneyChange < (2 * 100))) { real.one++; moneyChange = moneyChange - (1 * 100); } if ((moneyChange >= (2 * 100)) && (moneyChange < (5 * 100))) { real.two++; moneyChange = moneyChange - (2 * 100); } if ((moneyChange >= (5 * 100)) && (moneyChange < (10 * 100))) { real.five++; moneyChange = moneyChange - (5 * 100); } if ((moneyChange >= (10 * 100)) && (moneyChange < (20 * 100))) { real.ten++; moneyChange = moneyChange - (10 * 100); } if ((moneyChange >= (20 * 100)) && (moneyChange < (50 * 100))) { real.twenty++; moneyChange = moneyChange - (20 * 100); } if ((moneyChange >= (50 * 100)) && (moneyChange < (100 * 100))) { real.fifty++; moneyChange = moneyChange - (50 * 100); } if (moneyChange >= (100 * 100)) { real.hundred++; moneyChange = moneyChange - (100 * 100); } } printf("+-----------------------------------------------+\n"); printf("| PURCHASE VALUE: %-30lf|\n", purchase / 100); printf("| RECEIVED VALUE: %-30lf|\n", received / 100); printf("| MONEY CHANGE VALUE: %-26lf|\n", storage / 100); printf("+-----------------------------------------------+\n"); printf("| |\n"); printf("| VALUE | AMOUNT |\n"); printf("| R$0.01 | %-10d |\n", cents.one); printf("| R$0.05 | %-10d |\n", cents.five); printf("| R$0.10 | %-10d |\n", cents.ten); printf("| R$0.25 | %-10d |\n", cents.twentyFive); printf("| R$0.50 | %-10d |\n", cents.fifty); printf("| R$1 | %-10d |\n", real.one); printf("| R$2 | %-10d |\n", real.two); printf("| R$5 | %-10d |\n", real.five); printf("| R$10 | %-10d |\n", real.ten); printf("| R$20 | %-10d |\n", real.twenty); printf("| R$50 | %-10d |\n", real.fifty); printf("| R$100 | %-10d |\n", real.hundred); printf("| |\n"); printf("+-----------------------------------------------+\n"); } }
the_stack_data/86075440.c
/************************************************************************* * Name: huffman.c * Author: Marcus Geelnard * Description: Huffman coder/decoder implementation. * Reentrant: Yes * * This is a very straight forward implementation of a Huffman coder and * decoder. * * Primary flaws with this primitive implementation are: * - Slow bit stream implementation * - Maximum tree depth of 32 (the coder aborts if any code exceeds a * size of 32 bits). If I'm not mistaking, this should not be possible * unless the input buffer is larger than 2^32 bytes, which is not * supported by the coder anyway (max 2^32-1 bytes can be specified with * an unsigned 32-bit integer). * * On the other hand, there are a few advantages of this implementation: * - The Huffman tree is stored in a very compact form, requiring only * 10 bits per symbol (for 8 bit symbols), meaning a maximum of 320 * bytes overhead. * - The code should be fairly easy to follow, if you are familiar with * how the Huffman compression algorithm works. * * Possible improvements (probably not worth it): * - Partition the input data stream into blocks, where each block has * its own Huffman tree. With variable block sizes, it should be * possible to find locally optimal Huffman trees, which in turn could * reduce the total size. * - Allow for a few different predefined Huffman trees, which could * reduce the size of a block even further. *------------------------------------------------------------------------- * Copyright (c) 2003-2006 Marcus Geelnard * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would * be appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not * be misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source * distribution. * * Marcus Geelnard * marcus.geelnard at home.se *************************************************************************/ /************************************************************************* * Types used for Huffman coding *************************************************************************/ #include <inttypes.h> typedef struct { uint8_t *BytePtr; uint16_t BitPos; } huff_bitstream_t; typedef struct { int16_t Symbol; uint16_t Count; uint16_t Code; uint16_t Bits; } huff_sym_t; typedef struct huff_encodenode_struct huff_encodenode_t; struct huff_encodenode_struct { huff_encodenode_t *ChildA, *ChildB; int16_t Count; int16_t Symbol; }; typedef struct huff_decodenode_struct huff_decodenode_t; struct huff_decodenode_struct { huff_decodenode_t *ChildA, *ChildB; int16_t Symbol; }; /************************************************************************* * Constants for Huffman decoding *************************************************************************/ /* The maximum number of nodes in the Huffman tree is 2^(8+1)-1 = 511 */ #define MAX_TREE_NODES 511 /************************************************************************* * INTERNAL FUNCTIONS * *************************************************************************/ /************************************************************************* * _Huffman_InitBitstream() - Initialize a bitstream. *************************************************************************/ static void _Huffman_InitBitstream( huff_bitstream_t *stream, uint8_t *buf ) { stream->BytePtr = buf; stream->BitPos = 0; } /************************************************************************* * _Huffman_ReadBit() - Read one bit from a bitstream. *************************************************************************/ static uint16_t _Huffman_ReadBit( huff_bitstream_t *stream ) { uint16_t x, bit; uint8_t *buf; /* Get current stream state */ buf = stream->BytePtr; bit = stream->BitPos; /* Extract bit */ x = (*buf & (1<<(7-bit))) ? 1 : 0; bit = (bit+1) & 7; if( !bit ) { ++ buf; } /* Store new stream state */ stream->BitPos = bit; stream->BytePtr = buf; return x; } /************************************************************************* * _Huffman_Read8Bits() - Read eight bits from a bitstream. *************************************************************************/ static uint16_t _Huffman_Read8Bits( huff_bitstream_t *stream ) { uint16_t x, bit; uint8_t *buf; /* Get current stream state */ buf = stream->BytePtr; bit = stream->BitPos; /* Extract byte */ x = (*buf << bit) | (buf[1] >> (8-bit)); ++ buf; /* Store new stream state */ stream->BytePtr = buf; return x; } /************************************************************************* * _Huffman_RecoverTree() - Recover a Huffman tree from a bitstream. *************************************************************************/ static huff_decodenode_t * _Huffman_RecoverTree( huff_decodenode_t *nodes, huff_bitstream_t *stream, uint16_t *nodenum ) { huff_decodenode_t * this_node; /* Pick a node from the node array */ this_node = &nodes[*nodenum]; *nodenum = *nodenum + 1; /* Clear the node */ this_node->Symbol = -1; this_node->ChildA = (huff_decodenode_t *) 0; this_node->ChildB = (huff_decodenode_t *) 0; /* Is this a leaf node? */ if( _Huffman_ReadBit( stream ) ) { /* Get symbol from tree description and store in lead node */ this_node->Symbol = _Huffman_Read8Bits( stream ); // this_node->Symbol = _Huffman_Read16Bits( stream ); return this_node; } /* Get branch A */ this_node->ChildA = _Huffman_RecoverTree( nodes, stream, nodenum ); /* Get branch B */ this_node->ChildB = _Huffman_RecoverTree( nodes, stream, nodenum ); return this_node; } /************************************************************************* * PUBLIC FUNCTIONS * *************************************************************************/ /************************************************************************* * Huffman_Uncompress() - Uncompress a block of data using a Huffman * decoder. * in - Input (compressed) buffer. * out - Output (uncompressed) buffer. This buffer must be large * enough to hold the uncompressed data. * insize - Number of input bytes. * outsize - Number of output bytes. *************************************************************************/ void Huffman_Uncompress( uint8_t *in, uint8_t *out, uint16_t insize, uint16_t outsize ) { huff_decodenode_t nodes[MAX_TREE_NODES], *root, *node; huff_bitstream_t stream; uint16_t k, node_count; uint8_t *buf; /* Do we have anything to decompress? */ if( insize < 1 ) return; /* Initialize bitstream */ _Huffman_InitBitstream( &stream, in ); /* Recover Huffman tree */ node_count = 0; root = _Huffman_RecoverTree( nodes, &stream, &node_count ); /* Decode input stream */ buf = out; for( k = 0; k < outsize; ++ k ) { /* Traverse tree until we find a matching leaf node */ node = root; while( node->Symbol < 0 ) { /* Get next node */ if( _Huffman_ReadBit( &stream ) ) node = node->ChildB; else node = node->ChildA; } /* We found the matching leaf node and have the symbol */ *buf ++ = (uint8_t) node->Symbol; } }
the_stack_data/108437.c
//9-Faça um programa que use uma estrutura para armazenar os atributos de uma circunferência C,isto é, //raio e centro. O programa deve permitir as seguintes funcionalidades: a) calcular comprimento da //circunferência b) calcular a área do círculo envolto pela circunferência. Use funções. #include <stdio.h> #include <locale.h> typedef struct { float raio; float centro; }circ; float calc1(circ circulo){ // C = 2·π·r return 2 * 3.14 * circulo.raio; } float calc2(circ circulo){ // A = r² . π return 3.14 * (circulo.raio * circulo.raio); } int main(int argc, char const *argv[]) { circ Circ; printf("Insira o raio\n"); scanf("%f", &Circ.raio); printf("Insira o centro\n"); scanf("%f", &Circ.centro); printf("Comprimento: %.2f Área:%.2F\n", calc1(Circ), calc2(Circ)); return 0; }
the_stack_data/59511665.c
// PARAM: --set ana.activated "[['base','escape']]" #include <stdlib.h> #include <pthread.h> #include <assert.h> int *x; int *y; void *t_fun(void *arg) { *x = 3; return NULL; } int main() { pthread_t id; x = malloc(sizeof(int)); y = malloc(sizeof(int)); *x = 0; *y = 1; assert(*x == 0); assert(*y == 1); pthread_create(&id, NULL, t_fun, NULL); assert(*x == 0); // UNKNOWN assert(*y == 1); return 0; }
the_stack_data/596257.c
/* * Copyright (c) 2012 The Native Client Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include <stdio.h> #include <stdlib.h> /* Prototypes to disable inlining. */ int inner(const char *, const char *) __attribute__((noinline)); int middle(const char *) __attribute__((noinline)); int outer(char *) __attribute__((noinline)); int alloca_size(void) __attribute__((noinline)); int inner(const char *outer_local, const char *middle_frame) { const char local = 0; fprintf(stderr, "inner: outer_local = %p, &local = %p, " "middle_frame = %p\n", (void *) outer_local, (void *) &local, (void *) middle_frame); if (outer_local >= &local) { int inner_below_middle = middle_frame >= &local; int middle_below_outer = outer_local >= middle_frame; fprintf(stderr, "inner: stack grows downwards, " " middle_below_outer %d, inner_below_middle %d\n", middle_below_outer, inner_below_middle); return middle_below_outer && inner_below_middle; } else { int inner_above_middle = middle_frame <= &local; int middle_above_outer = outer_local <= middle_frame; fprintf(stderr, "inner: stack grows upwards, " " middle_above_outer %d, inner_above_middle %d\n", middle_above_outer, inner_above_middle); return middle_above_outer && inner_above_middle; } } int middle(const char *outer_local) { const char *frame = __builtin_frame_address (0); int retval; fprintf(stderr, "middle: outer_local = %p, frame = %p\n", (void *) outer_local, (void *) frame); retval = inner(outer_local, frame); /* fprintf also disables tail call optimization. */ fprintf(stderr, "middle: inner returned %d\n", retval); return retval != 0; } int outer(char *dummy) { const char local = 0; int retval; fprintf(stderr, "outer: &local = %p\n", (void *) &local); retval = middle(&local); /* fprintf also disables tail call optimization. */ fprintf(stderr, "outer: middle returned %d\n", retval); return retval != 0; } int alloca_size(void) { return 8; } int main (void) { char *dummy = __builtin_alloca(alloca_size()); int retval; fprintf(stderr, "main: dummy = %p\n", (void *) dummy); retval = outer(dummy); fprintf(stderr, "main: outer returned %d\n", retval); if (retval == 0) abort(); return 0; }
the_stack_data/39404.c
#include "stdio.h" #include "string.h" int main (int argc, char * argv[]) { const char kStr[] = "73167176531330624919225119674426574742355349194934" "96983520312774506326239578318016984801869478851843" "85861560789112949495459501737958331952853208805511" "12540698747158523863050715693290963295227443043557" "66896648950445244523161731856403098711121722383113" "62229893423380308135336276614282806444486645238749" "30358907296290491560440772390713810515859307960866" "70172427121883998797908792274921901699720888093776" "65727333001053367881220235421809751254540594752243" "52584907711670556013604839586446706324415722155397" "53697817977846174064955149290862569321978468622482" "83972241375657056057490261407972968652414535100474" "82166370484403199890008895243450658541227588666881" "16427171479924442928230863465674813919123162824586" "17866458359124566529476545682848912883142607690042" "24219022671055626321111109370544217506941658960408" "07198403850962455444362981230987879927244284909188" "84580156166097919133875499200524063689912560717606" "05886116467109405077541002256983155200055935729725" "71636269561882670428252483600823257530420752963450"; const unsigned int kAdjCount = 13; const unsigned int kNdigits = strlen(kStr); unsigned long max = 0; for (unsigned int i = 0; i < kNdigits -kAdjCount; i++) { unsigned long prod = 1; for (int j = 0; j < kAdjCount; j++) { prod *= (unsigned long)kStr[i+j] - '0'; } if (prod > max) { max = prod; } } printf("The largest %u adj product : %lu\n", kAdjCount, max); }
the_stack_data/390529.c
/******************************************************* * Written by Lerentis * * This file is part of C Course 2016 - HS-Bochum. * *******************************************************/ #include <stdio.h> void printSizeOf(double doubleArray[]); void printLength(double doubleArray[]); int main(int argc, char *argv[]) { int var = 5; int *varptr = &var; printf("%d \n", *varptr); printf("%p \n", varptr); /* an array with 5 elements */ double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0}; double *p; unsigned int i; p = balance; /* output each array element's value */ printf( "Array values using pointer\n"); for ( i = 0; i < (sizeof(balance) / sizeof(double)); i++ ) { printf("*(p + %d) : %f\n", i, *(p + i) ); } printf( "Array values using balance as address\n"); for ( i = 0; i < (sizeof(balance) / sizeof(double)); i++ ) { printf("*(balance + %d) : %f\n", i, *(balance + i) ); } printf( "Array values using java notation\n"); for ( i = 0; i < (sizeof(balance) / sizeof(double)); i++) { printf("balance[%d] : %f \n", i, balance[i]); } printSizeOf(balance); printLength(balance); return 0; } void printSizeOf(double doubleArray[]) { printf("sizeof of parameter: %d\n", (int) sizeof(doubleArray)); } void printLength(double doubleArray[]) { printf("Length of parameter: %d\n", (int)( sizeof(doubleArray) / sizeof(doubleArray[0]) )); }
the_stack_data/212642129.c
#include <stdio.h> int main(void) { int a, b; printf("Input a: "); scanf("%d", &a); printf("Input b: "); scanf("%d", &b); int s = a * b / 2; printf("The area is %d\n", s); return 0; }
the_stack_data/40762744.c
#include <stdio.h> int factorial(int n) { if (n == 0) { return 1; } return n * factorial(n - 1); } int main() { int n; scanf("%d", &n); if (n < 0) { printf("Factorial of a negative number is not defined\n"); return 0; } printf("Factorial of %d is %d\n", n, factorial(n)); return 0; }
the_stack_data/23574386.c
/* DWD/CrC */ #ifdef KLEE_SYM_PRINTF /* Copyright (C) 2004 Manuel Novoa III <[email protected]> * * GNU Library General Public License (LGPL) version 2 or later. * * Dedicated to Toni. See uClibc/DEDICATION.mjn3 for details. */ #include "_stdio.h" #include <stdarg.h> libc_hidden_proto(vfprintf) libc_hidden_proto(printf) int printf(const char * __restrict format, ...) { va_list arg; int rv; va_start(arg, format); rv = vfprintf(stdout, format, arg); va_end(arg); return rv; } libc_hidden_def(printf) #endif
the_stack_data/76900.c
#include<stdio.h> int main() { int a,b,c; scanf("%d",&a); for(c=a+1;;c++){ for(b=2;;b++){ if(c%b==0)break; } if(b==c)break; } printf("%d",c); return 0; }
the_stack_data/7949371.c
double recursive(double x, long n) { if (n == 0) return 1; double res = recursive(x, n / 2); return res * res * (n % 2 == 0 ? 1 : x); } double myPow(double x, int n) { if (x == 0 || x == 1 || n == 0) return 1; long m = n; double res = recursive(x > 0 ? x : -x, m > 0 ? m : -m); if (n < 0) res = 1 / res; return x < 0 && n % 2 == 1 ? -res : res; }
the_stack_data/94115.c
#include <stdio.h> int main(void) { int n1, n2, n3, n4, n5; printf("Enter ISBN: "); scanf("%d-%d-%d-%d-%d", &n1, &n2, &n3, &n4, &n5); printf("GS1 prefix: %d\n", n1); printf("Group identifier: %d\n", n2); printf("Publisher code: %d\n", n3); printf("Item number: %d\n", n4); printf("Check digit: %d\n", n5); return 0; }
the_stack_data/220454734.c
/* * https://gist.github.com/jcaesar/3049542 * http://www.it165.net/os/html/201308/5868.html ** */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include <unistd.h> #include <fcntl.h> #include <sys/epoll.h> #include <errno.h> #define MAX_LINE 1024 static struct config { char *path; char *file; int port; int threads; bool dynamic; } cfg; typedef struct event_ptr { int fd; int rein; char addr[16]; }event_ptr; static void usage() { printf("Usage: httpv <options> <url> \n" " Options: \n" " -p, --path <P> path of url \n" " -P, --port <P> port of host \n" " -t, --threads <N> Number of threads to use \n" " \n" " -f, --file <F> Load ip file \n" " -H, --header <H> Add header to request \n" " --latency Print latency statistics \n" " --timeout <T> Socket/request timeout \n" " -v, --version Print version details \n" " \n" " Numeric arguments may include a SI unit (1k, 1M, 1G)\n" " Time arguments may include a time unit (2s, 2m, 2h)\n"); } static int parse_args(struct config *cfg, char **headers, int argc, char* argv[]) { char **header = headers; int c; memset(cfg, 0, sizeof(struct config)); cfg->path = "/"; cfg->port = 80; cfg->file = NULL; cfg->dynamic = false; cfg->threads = 1000; while ((c = getopt(argc, argv, "f:P:p:t:H:d:h?")) != -1) { switch (c) { case 'f': cfg->file = optarg; break; case 'P': cfg->port = atoi(optarg); break; case 't': cfg->threads = atoi(optarg); break; case 'p': cfg->path = optarg; break; case 'H': *header++ = optarg; break; case 'h': case '?': default: return -1; } } *header = NULL; return 0; } static int create_and_connect( char *host , int *epfd) { struct hostent *hp; struct sockaddr_in addr; // epoll mask that contain the list of epoll events attached to a network socket static struct epoll_event event; int sock; int on = 1; if((hp = gethostbyname(host)) == NULL) { fprintf(stderr,"[NetTools] Invalid server name: %s\n", host); return -1; } bcopy(hp->h_addr, &addr.sin_addr, hp->h_length); addr.sin_port = htons(cfg.port); addr.sin_family = AF_INET; sock = socket(AF_INET, SOCK_STREAM, 0); // set socket to non blocking and allow port reuse if ( (setsockopt(sock,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(int)) || fcntl(sock, F_SETFL, O_NONBLOCK)) == -1) { perror("setsockopt || fcntl"); exit(1); } if( connect(sock, (struct sockaddr *)&addr, sizeof(struct sockaddr)) == -1 && errno != EINPROGRESS) { // connect doesn't work, are we running out of available ports ? if yes, destruct the socket if (errno == EAGAIN || errno == EWOULDBLOCK) { perror("connect is EAGAIN"); //close(sock); exit(1); } } else { /* epoll will wake up for the following events : * * EPOLLIN : The associated file is available for read(2) operations. * * EPOLLOUT : The associated file is available for write(2) operations. * * EPOLLRDHUP : Stream socket peer closed connection, or shut down writing * half of connection. (This flag is especially useful for writing simple * code to detect peer shutdown when using Edge Triggered monitoring.) * * EPOLLERR : Error condition happened on the associated file descriptor. * epoll_wait(2) will always wait for this event; it is not necessary to set it in events. */ event.events = EPOLLIN | EPOLLOUT | EPOLLRDHUP | EPOLLERR | EPOLLET; //Edgvent.events = EPOLLOUT | EPOLLIN | EPOLLRDHUP | EPOLLERR | EPOLLET; event.data.ptr = malloc(sizeof(event_ptr)); struct event_ptr *ptr = event.data.ptr; bzero(ptr, sizeof(event_ptr)); ptr->fd = sock; ptr->rein = 0; strcpy(ptr->addr, host); //ptr->addr[strlen(host)] = '\0'; // add the socket to the epoll file descriptors if(epoll_ctl((int)*epfd, EPOLL_CTL_ADD, sock, &event) != 0) { perror("epoll_ctl, adding socket\n"); exit(1); } } return 0; } /* reading waiting errors on the socket * return 0 if there's no, 1 otherwise */ int socket_check(int fd) { int ret; int code; int len = sizeof(int); ret = getsockopt(fd, SOL_SOCKET, SO_ERROR, &code, &len); if ((ret || code)!= 0) return 1; return 0; } void stringlink(char *s, char *t) { while (*s != '\0') { s++; } while (*t != '\0') { *s++ = *t++; } *s = '\0'; } char* substring(const char* str, size_t begin, size_t len) { if (str == 0 || strlen(str) == 0 || strlen(str) < begin || strlen(str) < (begin+len)) return 0; return strndup(str + begin, len); } char *substr(char *haystack, char *begin, char *end) { char *ret, *r; char *b = strstr(haystack, begin); if (b) { char *e = strstr(b, end); if(e) { int offset = e - b; int retlen = offset - strlen(begin); if ((ret = malloc(retlen + 1)) == NULL) return NULL; strncpy(ret, b + strlen(begin), retlen); return ret; } } return NULL; } void main(int argc, char* argv[]) { char *url, **headers; headers = malloc((argc / 2) * sizeof(char *)); if (parse_args(&cfg, headers, argc, argv)) { usage(); exit(1); } char **h; char header_name[32]; char header_value[200]; char header[1024]; char header_tmp[232]; event_ptr * ptr; if (cfg.file) { FILE *fp; char buf[MAX_LINE]; /*缓冲区*/ int n, len ; fp = fopen(cfg.file, "r"); if (fp == NULL) { printf("file not exist :%s\n", cfg.file); exit(1); } n = 0; int epfd; static struct epoll_event *events; // create the special epoll file descriptor epfd = epoll_create(cfg.threads); // allocate enough memory to store all the events in the "events" structure if (NULL == (events = calloc(cfg.threads, sizeof(struct epoll_event)))) { perror("calloc events"); exit(1); }; int rn = 0; master_worker: while(fgets(buf, MAX_LINE, fp) != NULL) { len = strlen(buf); buf[len-1] = '\0'; /* 去掉换行符 */ if(strlen(buf) >= 7 && create_and_connect(buf, &epfd) != 0) { fprintf (stderr, "create and connect : %s\n", buf); } ++n; ++rn; if(rn > cfg.threads) goto epoll_worker; } if (rn == 0) exit(0); epoll_worker: sprintf(header, "GET %s HTTP/1.1\r\n", cfg.path); rn = 0; for (h = headers; *h; h++) { char *p = strchr(*h, ':'); if (p && p[1] == ' ') { bzero(header_name, 32); bzero(header_value, 200); bzero(header_tmp, 232); strncpy(header_name, *h, strlen(*h) - strlen(p)); strcpy(header_value, p + 2); sprintf(header_tmp, "%s: %s\r\n", header_name, header_value); stringlink(header, header_tmp); //printf("p=%p(%d), %s => %s\n", p, strlen(p), header_name, header_value); } } stringlink(header, "\r\n"); int header_len = strlen(header); char *hhh = malloc( header_len * sizeof(char) + 1); strcpy(hhh, header); printf("%s", hhh); char buffer[2049]; int buffersize = 2048; int count, i, datacount; int http_status; char *http_servername = NULL; char *http_title = NULL; while(1) { count = epoll_wait(epfd, events, cfg.threads, 500); if(count == 0) break; for(i=0;i<count;i++) { ptr = events[i].data.ptr; //printf("count=%d,fd=%d ,ip=%s, events[i].events=%d\n", count, ptr->fd, ptr->addr, events[i].events); if ((events[i].events & (EPOLLHUP | EPOLLERR)) || strlen(ptr->addr) == 0) { epoll_ctl(epfd, EPOLL_CTL_DEL, ptr->fd, NULL); //fprintf (stderr, "epoll error %d\n", ptr->fd); continue; } if (events[i].events & EPOLLOUT) //socket is ready for writing { // verify the socket is connected and doesn't return an error if(socket_check(ptr->fd) != 0) { perror("write socket_check"); continue; } else { int total = header_len; while(1) { datacount = send(ptr->fd, hhh, header_len, 0); if(datacount < 0) { if (errno == EINTR || errno == EAGAIN) { usleep(1000); continue; } } if (datacount == total) { events[i].events = EPOLLIN | EPOLLHUP | EPOLLERR; if(epoll_ctl(epfd, EPOLL_CTL_MOD, ptr->fd, events) != 0) { perror("epoll_ctl, modify socket"); continue; } break; } total -= datacount; hhh += datacount; } } } if (events[i].events & (EPOLLIN )) //socket is ready for reading { // verify the socket is connected and doesn't return an error if(socket_check(ptr->fd) != 0) { fprintf (stderr, " [ %s->%d] read socket_check : [%d]%s\n", ptr->addr, ptr->fd, errno, strerror(errno)); //epoll_ctl(epfd, EPOLL_CTL_DEL, ptr->fd, NULL); continue; } else { memset(buffer,0x0,buffersize); int n = 0; while (1) { datacount = read(ptr->fd, buffer +n , buffersize); if(datacount == -1) { ++ptr->rein; if (ptr->rein > 5) { epoll_ctl(epfd, EPOLL_CTL_DEL, ptr->fd, NULL); break; } if (errno == EAGAIN) { usleep(1000); continue; } }else if(datacount == 0) { break; } //printf("%s=%d=%d\n", buffer, n, datacount); n += datacount; } /* if((datacount = recv(ptr->fd, buffer, buffersize, 0)) < 0 ) { ++ptr->rein; fprintf (stderr, "[ %s->%d] recv failed : %s\n", ptr->addr, ptr->fd, strerror(errno)); if(ptr->rein > 5) { epoll_ctl(epfd, EPOLL_CTL_DEL, ptr->fd, NULL); } continue; } */ printf("%s\n", buffer); char *http_status = substring(buffer, 9, 3); http_servername = substr(buffer, "Server: ", "\r\n"); http_title = substr(buffer, "<title>", "</title>"); fprintf (stdout, "%s\t%s\t%s\t%s\n", ptr->addr, http_status, http_servername, http_title); if(http_status != NULL) free(http_status); if(http_servername != NULL) free(http_servername); if(http_title != NULL) free(http_title); epoll_ctl(epfd, EPOLL_CTL_DEL, ptr->fd, NULL); //usleep(10000); } } } } goto master_worker; } //printf("headers: %s\npath: %s\nport: %d\n", *headers, cfg.path, cfg.port); }
the_stack_data/161081557.c
#include "syscall.h" #include "stdlib.h" /* * Opens file and closes it immediately. * * argc - equals 1 * argv[0] - file that exists in nachos_home directory * * returns - 0 on success */ int main(int argc, char **argv) { int fd = -1; // Make sure we have been called with correct number of arguments. assert(argc == 1); // Open file and close it immediately. fd = open(argv[0]); assert(-1 != fd); assert(0 == close(fd)); return 0; }
the_stack_data/170451778.c
#include <stdio.h> #include <stdlib.h> void f1(void) { printf("in f1()\n"); } void f2(void) { printf("in f2()\n"); } void f3(void) { printf("in f3()\n"); } int main(int argc, char const *argv[]) { printf("Registering the at-exit functions ..."); if (atexit(f1) || atexit(f2) || atexit(f3)) printf("failed.\n"); else printf("done.\n"); printf("Now exiting...\n"); exit(0); // _Exit(0); // not call fn()s }
the_stack_data/655227.c
#include <stdio.h> #define N 239 int wcount(char*); int main(int argc, char **argv) { char str[N] = { 0 }; gets(str); printf("%d", wcount(str)); return 0; } int wcount(char *s) { int outword, count, i; outword = count = i = 0; while(s[i] != '\n') { while(s[i] == ' ') { i++; outword++; } if (outword) { count++; outword = 0; } i++; } return count; }
the_stack_data/179830516.c
/** * memops benchmark in C * * gcc memops.c -o memops */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> int main(int argc, char **argv) { int N = 1024*1024, M = 800; float startTime = (float)clock()/(CLOCKS_PER_SEC/1000); int final = 0; char *buf = (char*)malloc(N); for (int t = 0; t < M; t++) { for (int i = 0; i < N; i++) buf[i] = (i + final)%256; for (int i = 0; i < N; i++) final += buf[i] & 1; final = final % 1000; } float endTime = (float)clock()/(CLOCKS_PER_SEC/1000); printf("duration: %f ms\n", (endTime-startTime)); return 0; }
the_stack_data/74453.c
int primo(unsigned int val) { int count = 0, div =0; for (count = 1; count < val; count += 1) { if (val % count == 0) div += 1; if (div > 2) return 0; } return 1; } int main(void){ int num = 10000; int _primo = primo(num); return 0; }
the_stack_data/53315.c
#include <stdio.h> #include <sqlite3.h> static int callback(void *NotUsed, int argc, char **argv, char **azColName){ int i; for(i=0; i<argc; i++){ printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } int main(int argc, char **argv){ sqlite3 *db; char *zErrMsg = 0; int rc; if( argc!=3 ){ fprintf(stderr, "Usage: %s DATABASE SQL-STATEMENT\n", argv[0]); return(1); } rc = sqlite3_open(argv[1], &db); if( rc ){ fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); sqlite3_close(db); return(1); } rc = sqlite3_exec(db, argv[2], callback, 0, &zErrMsg); if( rc!=SQLITE_OK ){ fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } sqlite3_close(db); return 0; }
the_stack_data/115828.c
float d = 72; void MAIN() { float r; r = d *= 70; print("d 5040.000000"); printid(d); }
the_stack_data/68888799.c
/*- * Copyright (c) 1990 The Regents of the University of California. * All rights reserved. * * This code is derived from software contributed to Berkeley by * Chris Torek. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed by the University of * California, Berkeley and its contributors. * 4. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)fgetc.c 5.3 (Berkeley) 1/20/91"; #endif /* LIBC_SCCS and not lint */ #include <stdio.h> int fgetc(fp) FILE *fp; { return (__sgetc(fp)); }
the_stack_data/734810.c
/* * split_path.c * * Created on: Apr 22, 2015 * Author: Nick Pershin * * Last edited on: Apr 22, 2015 * Editor: Nick Pershin * * * BUILD DEBUG: * gcc -std=c99 -I../.. -Wall -g -o split_path split_path.c * BUILD RELEASE: * gcc -std=c99 -I../.. -Wall -O3 -o split_path split_path.c * * RUN: * ./split_path */ #include <stdio.h> #include <stdlib.h> #include <string.h> /* void split_path_file(char** p, char** f, char *pf) { // If pf == slash, then there is no directory component char *slash = pf, *next; while ((next = strpbrk(slash + 1, "\\/"))) slash = next; if (pf != slash) slash++; *p = strndup(pf, slash - pf); *f = strdup(slash); } */ void split_path_file(char **p, char **f, char *pf) { // find the last delimiter char *z; for (z = pf+strlen(pf); z >= pf; z--) { if (*z == '/' || *z == '\\') break; } if (z >= pf) { // there is a delimiter: construct separate fragments for path and filename //printf("\t--> %li\n", z-pf); *p = malloc(z-pf+1); strncpy(*p, pf, z-pf); (*p)[z-pf] = '\0'; *f = malloc(strlen(z)); strcpy(*f, z+1); } else { // there is no delimiter: the entire string must be a filename *p = NULL; *f = malloc(strlen(pf)+1); strcpy(*f, pf); } } int main(int argc, char **argv) { //char *path = "/bin/dubin/mkdir"; //char *path = "output_data/TEST/Unzipped_Content/Организ.\\ пр-ва\\ на\\ предпр.\\ ЖКХ\\ РП.docx"; char *path = "output_data/TEST/Unzipped_Content/Организ. пр-ва на предпр. ЖКХ РП.docx"; //char *path = "Организ. пр-ва на предпр. ЖКХ РП.docx"; char *p, *f; int len = strlen(path); printf("\n\tINPUT: [%s] (length: %d)\n\n", path, len); split_path_file(&p, &f, path); if(p != NULL) { len = strlen(p); printf("\tPATH: [%s] (length: %d)\n\n", p, len); } else { printf("\tPATH: NULL\n\n"); } len = strlen(f); printf("\tFILE: [%s] (length: %d)\n\n", f, len); return 0; }
the_stack_data/132952857.c
#include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/mman.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #define NUM_PAGE 2 int identifyARG(int argc,char **argv); int readMMap(const char *pathName); int writeMMap(const char *pathName); int initMMapFile(const char *pathName); int main(int argc,char **argv) { switch(identifyARG(argc,argv)) { case 0://读取 return readMMap(argv[1]); case 1://写入 return writeMMap(argv[1]); case 2://初始化文件 return initMMapFile(argv[1]); default://错误 return -1; } return 0; } int identifyARG(int argc,char **argv) { if(argc != 3) { printf("参数列表数量错误\n"); return -1; } else { if(strcmp(argv[2],"-r") == 0) { printf("内存映射读取模式\n"); return 0; } else if(strcmp(argv[2],"-w") == 0) { printf("内存映射写入模式\n"); return 1; } else if(strcmp(argv[2],"-i") == 0) { printf("文件初始化模式\n"); return 2; } else { printf("指令不存在\n"); return -1; } } } int initMMapFile(const char *pathName) { off_t fileSize = getpagesize() * NUM_PAGE; if(truncate(pathName,fileSize) != 0) { printf("修改文件大小失败\n"); } printf("将改变文件大小为:%dkb\n",fileSize/1024); int fd = open(pathName,O_WRONLY); printf("fd:%d\n",fd); if(fd < 0) { printf("文件无法打开"); } char buff[1024] = {0}; memset(buff,' ',sizeof(buff)); buff[1023] = '\n'; ssize_t retval = 0; int i = 0; do { retval = write(fd,buff,sizeof(buff)); i++; }while(i < 4*NUM_PAGE); printf("i:%d\n",i); close(fd); return 0; } int readMMap(const char *pathName) { int fd = open(pathName,O_RDONLY); printf("fd:%d\n",fd); if(fd < 0) { printf("文件无法打开"); } char *buff = mmap( NULL, getpagesize() * NUM_PAGE, PROT_READ, MAP_SHARED, fd, 0); printf("ShareMemory:\n%s\n",buff); munmap(buff,256); close(fd); return 0; } int writeMMap(const char *pathName) { int fd = open(pathName,O_RDWR); printf("fd:%d\n",fd); if(fd < 0) { printf("文件无法打开"); } char *buff = mmap( NULL, getpagesize(), PROT_WRITE, MAP_SHARED, fd, 0); memset(buff,' ',getpagesize()); munmap(buff,getpagesize()); buff = mmap( NULL, 256, PROT_WRITE, MAP_SHARED, fd, getpagesize() * 1); strcpy(buff,"hellohelloworld"); munmap(buff,256); close(fd); return 0; }
the_stack_data/156392097.c
/** * _strlen_recursion - gets strlen of s via recursive algorithm * * @s: string to check length of * * Return: int containing length of string */ int _strlen_recursion(char *s) { if (!*s) return (0); return (1 + _strlen_recursion(s + 1)); }