Stats *Stats_recreate(double sum, double sumsq, unsigned long n, double min, double max ) { Stats *st = malloc(sizeof(Stats)); check_mem(st); st->sum = sum; st->sumsq = sumsq; st->n = n; st->min = min; st->max = max; return st; error: return NULL; }
int test_check(char *file_name) { FILE *input = NULL; char *block = NULL; block = malloc(100); check_mem(block); input = fopen(file_name, "r"); check(input, "Failed to open %s", file_name); free(block); fclose(input); return 0; error: if(block) free(block); if(input) fclose(input); return -1; }
int test_sentinel(int code) { char *temp = malloc(100); check_mem(temp); switch(code) { case 1: log_info("it worked"); break; default: sentinel("I shouldn't run"); } free(temp); return 0; error: if(temp) free(temp); return -1; }
int Renderer_createTexture( const char *pTFile, bool pMipmaps ) { Texture *t = NULL; if( renderer && TextureArray_checkSize( &renderer->mTextures ) ) { t = Texture_new(); check_mem( t ); // texture creation from file check( Texture_loadFromFile( t, pTFile, pMipmaps ), "Error in texture creation.\n" ); // storage int index = renderer->mTextures.cpt++; renderer->mTextures.data[index] = t; return index; } error: Texture_destroy( t ); return -1; }
int Filter_add(StateEvent state, filter_cb cb, bstring load_path, tns_value_t *config) { darray_t *filters = Filter_lookup_create(state); check(filters != NULL, "Invalid filter state: %d given for filter %s", state, bdata(load_path)); Filter *filter = darray_new(filters); check_mem(filter); filter->state = state; filter->cb = cb; filter->load_path = bstrcpy(load_path); filter->config = config; darray_attach(filters, filter); darray_push(filters, filter); return 0; error: return -1; }
void List_unshift(List *list, void *value) { ListNode *node = calloc(1, sizeof(ListNode)); check_mem(node); node->value = value; if(list->first == NULL) { list->first = node; list->last = node; } else { node->next = list->first; list->first->prev = node; list->first = node; } list->count++; error: return; }
int Renderer_createShader( const char *pVFile, const char *pFFile ) { Shader *s = NULL; if( renderer && ShaderArray_checkSize( &renderer->mShaders ) ) { s = Shader_new(); check_mem( s ); // shader creation and linking check( Shader_buildFromFile( s, pVFile, pFFile ), "Error in shader creation.\n" ); // storage int index = renderer->mShaders.cpt++; renderer->mShaders.data[index] = s; return index; } error: Shader_destroy( s ); return -1; }
CpuTimes *cpu_times_percent(bool percpu, CpuTimes *prev_times) { CpuTimes *current = NULL; CpuTimes *t; int i, ncpus = percpu ? cpu_count(1) : 1; CpuTimes *ret; check(prev_times, "Need a reference point. prev_times can't be NULL"); current = cpu_times(percpu); check(current, "Couldn't obtain CPU times"); ret = (CpuTimes *)calloc(ncpus, sizeof(CpuTimes)); check_mem(ret); for (i = 0; i < ncpus; i++) { t = calculate_cpu_times_percentage(prev_times + i, current + i); *(ret + i) = *t; free(t); } free(current); return ret; error: free(current); return NULL; }
int http_receive_payload(int sockfd, char **payload, int content_length) { *payload = NULL; ssize_t recv_size = 0; *payload = (char *)calloc(sizeof(char), content_length + 1); check_mem(payload); recv_size = read_all(sockfd, *payload, content_length); debug("%s", *payload); if (recv_size == content_length) { debug("Read complete Http payload."); } else if (recv_size == 0) { log_err("End of TCP stream."); return ERR_EOF; } else { log_err("Error while reading TCP stream."); // TODO handle exit(-1); } return HTTP_SUCCESS; }
// Copies a node and its children. // // node - The node to copy. // ret - A pointer to where the new copy should be returned to. // // Returns 0 if successful, otherwise returns -1. int qip_ast_freturn_copy(qip_ast_node *node, qip_ast_node **ret) { int rc; check(node != NULL, "Node required"); check(ret != NULL, "Return pointer required"); qip_ast_node *clone = qip_ast_freturn_create(NULL); check_mem(clone); rc = qip_ast_node_copy(node->freturn.value, &clone->freturn.value); check(rc == 0, "Unable to copy return value"); if(clone->freturn.value) clone->freturn.value->parent = clone; *ret = clone; return 0; error: qip_ast_node_free(clone); *ret = NULL; return -1; }
int test_check(char *file_name) { FILE *input = NULL; char *block = NULL; block = malloc(100); check_mem(block); // should work input = fopen(file_name, "r"); check(input, "Failed to open %s", file_name); free(block); fclose(input); return 0; error: printf("[goto error] at test_check\n"); if(block) free(block); if(input) fclose(input); return -1; }
static inline DArray *Hashmap_find_bucket(Hashmap *map, void *key, int create, uint32_t *hash_out) {//caller fn will include 1 or 0 for int create true or false uint32_t hash = map->hash(key); int bucket_n = hash % DEFAULT_NUMBER_OF_BUCKETS;//finds bucket, will always find a bucket no matter how big check(bucket_n >= 0, "Invalid bucket found: %d", bucket_n); *hash_out = hash; //store it for the return so caller can use it. I forget how caller is supposed to use this DArray *bucket = DArray_get(map->buckets, bucket_n); if(!bucket && create) {//creates bucket if none found //new bucket, set it up bucket = DArray_create(sizeof(void *), DEFAULT_NUMBER_OF_BUCKETS); check_mem(bucket); DArray_set(map->buckets, bucket_n, bucket); } return bucket; error: return NULL; }
Node_T create_node(Node_T father, SuffixTreeIndex_T start, SuffixTreeIndex_T end, SuffixTreeIndex_T position) { /*Allocate a node.*/ Node_T node = malloc(sizeof(struct Node_T)); check_mem(node); node->left_son = NULL; node->right_sibling = NULL; node->left_sibling = NULL; node->suffix_link = NULL; node->father = father; node->path_position = position; node->edge_label_start = start; node->edge_label_end = end; return node; error: if(node) free(node); return NULL; }
// Appends an expression to the end of the block. // // block - The block to append the expression to. // expr - The expression to append. // // Returns 0 if successful, otherwise returns -1. int qip_ast_block_add_expr(struct qip_ast_node *block, struct qip_ast_node *expr) { // Validate. check(block != NULL, "Block is required"); check(block->type == QIP_AST_TYPE_BLOCK, "Block node is invalid type: %d", block->type); check(expr != NULL, "Expression is required"); // Append expression to block. block->block.expr_count++; block->block.exprs = realloc(block->block.exprs, sizeof(qip_ast_node*) * block->block.expr_count); check_mem(block->block.exprs); block->block.exprs[block->block.expr_count-1] = expr; // Assign parent reference to expression. expr->parent = block; return 0; error: return -1; }
void lapack_dsteqr(int nn, int ldz, dreal *alph, dreal *beta, dreal *zz) { int nwork, info; char compz = 'I'; dreal *work = NULL; nwork = (1 >= 2*nn-2) ? 1 : 2*nn-2; work = (dreal *) calloc(nwork, sizeof(dreal)); check_mem(work, "work"); dsteqr_(&compz, &nn, alph, beta, zz, &ldz, work, &info); freeup(work); return; error: if(work) freeup(work); abort(); }
static inline DArray *Hashmap_find_bucket(Hashmap *map, void *key, int create, uint32_t *hash_out) { uint32_t hash = map->hash(key); int bucket_n = hash % DEFAULT_NUMBER_OF_BUCKETS; check(bucket_n >= 0, "Invalid bucket found: %d", bucket_n); *hash_out = hash; DArray *bucket = DArray_get(map->buckets, bucket_n); if (!bucket && create) { bucket = DArray_create(sizeof(void *), DEFAULT_NUMBER_OF_BUCKETS); check_mem(bucket); DArray_set(map->buckets, bucket_n, bucket); } return bucket; error: return NULL; }
void lapack_dsyev(int nn, dreal *AA, dreal *ww) { int lda, lwork, info; char jobz = 'V', uplo = 'U'; dreal *work = NULL; lda = (1 > nn) ? 1 : nn; lwork = (1 > 3*nn-1) ? 1 : 3*nn-1; work = (dreal *) calloc(lwork, sizeof(dreal)); check_mem(work, "work"); dsyev_(&jobz, &uplo, &nn, AA, &lda, ww, work, &lwork, &info); freeup(work); return; error: if(work) freeup(work); abort(); }
// Adds an argument to a function. // // node - The function node. // farg - The argument to add. // // Returns 0 if successful, otherwise returns -1. int qip_ast_function_add_arg(qip_ast_node *node, qip_ast_node *farg) { check(node != NULL, "Node required"); check(node->type == QIP_AST_TYPE_FUNCTION, "Node type must be 'function'"); check(farg != NULL, "Argument is required"); // Append argument to function. node->function.arg_count++; node->function.args = realloc(node->function.args, sizeof(qip_ast_node*) * node->function.arg_count); check_mem(node->function.args); node->function.args[node->function.arg_count-1] = farg; // Link property to function. farg->parent = node; return 0; error: return -1; }
// Starts a server. Once a server is started, it can accept messages over TCP // on the bind address and port number specified by the server object. // // server - The server to start. // // Returns 0 if successful, otherwise returns -1. int sky_server_start(sky_server *server) { int rc; assert(server != NULL); check(server->state == SKY_SERVER_STATE_STOPPED, "Server already running"); check(server->port > 0, "Port required"); // Initialize socket info. server->sockaddr = calloc(1, sizeof(struct sockaddr_in)); check_mem(server->sockaddr); server->sockaddr->sin_addr.s_addr = INADDR_ANY; server->sockaddr->sin_port = htons(server->port); server->sockaddr->sin_family = AF_INET; // Create socket. server->socket = socket(AF_INET, SOCK_STREAM, 0); check(server->socket != -1, "Unable to create a socket"); // Set socket for reuse. int optval = 1; rc = setsockopt(server->socket, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); check(rc == 0, "Unable to set socket for reuse"); // Bind socket. rc = bind(server->socket, (struct sockaddr*)server->sockaddr, sizeof(struct sockaddr_in)); check(rc == 0, "Unable to bind socket"); // Listen on socket. rc = listen(server->socket, SKY_LISTEN_BACKLOG); check(rc != -1, "Unable to listen on socket"); // Update server state. server->state = SKY_SERVER_STATE_RUNNING; return 0; error: sky_server_stop(server); return -1; }
UsersInfo *get_users() { uint32_t nusers = 100; UsersInfo *ret = (UsersInfo *)calloc(1, sizeof(UsersInfo)); Users *users = (Users *)calloc(nusers, sizeof(Users)); Users *u = users; struct utmp *ut; check_mem(ret); check_mem(users); ret->nitems = 0; ret->users = users; while (NULL != (ut = getutent())) { if (ut->ut_type != USER_PROCESS) continue; u->username = strdup(ut->ut_user); check_mem(u->username); u->tty = strdup(ut->ut_line); check_mem(u->tty); u->hostname = strdup(ut->ut_host); check_mem(u->hostname); u->tstamp = ut->ut_tv.tv_sec; ret->nitems++; u++; if (ret->nitems == nusers) { /* More users than we've allocated space for. */ nusers *= 2; users = (Users *)realloc(users, sizeof(Users) * nusers); check_mem(users); ret->users = users; u = ret->users + ret->nitems; /* Move the cursor to the correct value in case the realloc moved the memory */ } } endutent(); return ret; error: free_users_info(ret); return NULL; }
void List_push(List *list, void *value) { List_check(list); check(list, "Can't push to NULL list"); ListNode *node = calloc(1, sizeof(ListNode)); check_mem(node); node->value = value; if(list->last == NULL) { list->first = node; list->last = node; } else { list->last->next = node; node->prev = list->last; list->last = node; } list->count++; error: return; }
/* token_to_node: Convert a token structure into a node structure */ struct node *token_to_node( struct token t ) { struct node *newn; newn = malloc(NSIZE); check_mem(newn); if( t.tag == INT ) { newn->tag = NUM; newn->num = t.num; } else { newn->tag = NAME; newn->str = t.str; } return newn; error: return NULL; }
int main(int argc, char* argv[]) { int ch; pid_t pid = getpid(); acl::string action("fds"); while ((ch = getopt(argc, argv, "ha:p:")) > 0) { switch (ch) { case 'h': usage(argv[0]); return 0; case 'a': action = optarg; break; case 'p': pid = (pid_t) atoi(optarg); if (pid < 0) pid = getpid(); break; default: break; } } bool ret; acl::log::stdout_open(true); if (action == "fds") { ret = check_fds(pid); } else if (action == "mem") { ret = check_mem(pid); } else { printf("action: %s not support yet!\r\n", action.c_str()); return 1; } return ret ? 0 : 1; }
static inline int handler_recv_parse(Handler *handler, HandlerParser *parser) { log_info("handler_recv_parse"); zmq_msg_t *inmsg = NULL; check(handler->running, "Called while handler wasn't running, that's not good."); inmsg = calloc(sizeof(zmq_msg_t), 1); int rc = 0; check_mem(inmsg); rc = zmq_msg_init(inmsg); check(rc == 0, "Failed to initialize message."); taskstate("recv"); rc = mqrecv(handler->recv_socket, inmsg, 0); check(rc == 0, "Receive on handler socket failed."); check(handler->running, "Handler marked as not running."); rc = HandlerParser_execute(parser, zmq_msg_data(inmsg), zmq_msg_size(inmsg)); log_info("handler_recv_parse - HandlerParser_execute %d", rc); check(rc == 1, "Failed to parse message from handler."); check(parser->target_count > 0, "Message sent had 0 targets: %.*s", (int)zmq_msg_size(inmsg), (char *)zmq_msg_data(inmsg)); zmq_msg_close(inmsg); free(inmsg); return 0; error: if(inmsg) { zmq_msg_close(inmsg); free(inmsg); } return -1; }
int PQueue_push(PQueue *p_queue, void *item, int priority) { PQueueNode *node = malloc(sizeof(PQueueNode)); check_mem(node); node->item = item; node->priority = priority; int rc = Hashmap_set(p_queue->map, item, node); check(rc != -1, "Failed to set hash"); rc = BHeap_insert(p_queue->heap, node); if(rc == -1) { Hashmap_delete(p_queue->map, item); sentinel("Failed to push noe"); } return 1; error: if(node) free(node); return -1; }
sac * sac_new_n(int ntr) /* creat sac struct array */ { int i=0; /* allocate space */ sac *tr=NULL; tr = (sac *)calloc(ntr, sizeof(sac)); check_mem(tr); /* initialize */ for (i=0;i<ntr;i++) { tr[i].npts = 0; tr[i].iftype = 1; tr[i].nvhdr = 6; } return tr; error: return NULL; }
// Creates a lock file for the table. // // table - The table to lock. // // Returns 0 if successful, otherwise returns -1. int sky_table_lock(sky_table *table) { check(table != NULL, "Table required to lock"); // Construct path to lock. bstring path = bformat("%s/%s", bdata(table->path), SKY_LOCK_NAME); check_mem(path); // Open file with an exclusive lock. If this fails then it means another // process already has obtained a lock. table->lock_file = fopen(bdata(path), "w"); check(table->lock_file != NULL, "Table is already locked: %s", bdata(table->path)); // Clean up. bdestroy(path); return 0; error: bdestroy(path); return -1; }
struct ListNode *insert(int data, struct ListNode* head) { struct ListNode *p = head->next; struct ListNode *t = NULL; t = malloc(sizeof(struct ListNode)); check_mem(t); t->m_nKey = data; if(NULL == p) { t->next = p; head->next = t; } else { t->next = p; head->next = t; } return head; error: free(t); return head; }
int real__to_string(data_t **args, argc_t argc, data_t *ret, scope_t *scope) { (void) argc; REAL_TYPE n = args[0]->value.real; if (n <= 0) { n = -n + 1; } char *string = gc_add(scope->gc, malloc(sizeof(char) * (log10(n) + 2 + 20))); check_mem(string); sprintf(string, ((n < 0) ? "-%lf" : "%lf"), args[0]->value.real); ret->type = construct_type(tid_string, NULL, scope->gc); ret->value.string = string; return 0; error: return -1; }
static int fs_map_internal(struct fs_map *file) { struct stat sb; errno = 0; int fd = open(file->path, O_RDWR); check(errno == 0, "Could not open file for reading"); fstat(fd, &sb); check(sb.st_size, "File has no size"); file->size = sb.st_size; int flags = PROT_READ | PROT_WRITE; file->data = mmap(NULL, file->size, flags, MAP_SHARED, fd, 0); check_mem(file->data); close(fd); return 0; error: if(fd) close(fd); return -1; }